<?php

namespace App\Service\OpenShop\FeishuMini;

use App\Enums\OpenShop\FeishuMini\ProgrammingEnum;
use App\Enums\OpenShop\FeishuMini\SandTableEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Exceptions\Custom\ResponseHttpException;
use App\Http\Middleware\OpenShop\WangGuiCityByPower;
use App\Library\Common\DateTool;
use App\Library\Guanyuan\GuanyuanTool;
use App\Library\Rms\RmsShopApi;
use App\Models\Common\CityTerritorialBoundaryModel;
use App\Models\Common\ConfigModel;
use App\Models\Common\MapNationalBrandShopModel;
use App\Models\Common\MapNationalCommunityModel;
use App\Models\Common\MapNationalIndustrialParkModel;
use App\Models\Common\MapNationalStreetModel;
use App\Models\Common\MapNationalUniversitiesModel;
use App\Models\Common\MapTownshipPlanAreaModel;
use App\Models\Common\ResourcesModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Guanyuan\GuanyuanSyncShopBusinessModel;
use App\Models\Guanyuan\GuanyuanSyncShopListModel;
use App\Models\OpenShop\Common\SiteLocationMallModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationExamineLogModel;
use App\Models\OpenShop\Wanggui\WangguiSiteDistrictModel;
use App\Models\Wanggui\BusinessAoiModel;
use App\Models\Wanggui\SandTablePolymerizeDotInfoModel;
use App\Service\Api\WangguiApiService;
use App\Service\BaseService;
use App\Service\OpenShop\Feishu\ConfigService;
use App\Service\OpenShop\SiteLocation\GuanyuanDataService;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\WaiMai\WaiMaiAnalysisService;
use Carbon\Carbon;
use Guanguans\Notify\Factory;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Redis;

class SandTableService extends BaseService
{

    /**
     * 获得筛选看板
     * @return array
     */
    public static function sift(): array
    {
        $data   = [];
        $data[] = [
            'name'   => '夸父品牌',
            'select' => collect(ProgrammingEnum::KF_SHOP_STATUS_SELECT_MAPPING)->map(function ($shop, $index) {
                return [
                    'name' => $shop,
                    'key'  => ProgrammingEnum::KF_SHOP_SAND_TABLE_KEY_MAPPING[$index] ?? 'kfShop',
                ];
            })->values()->toArray()
        ];
        $data[] = [
            'name'   => '网规类型',
            'select' => collect(ProgrammingEnum::PROGRAMMING_MAPPING)->map(function ($type, $index) {
                return [
                    'name' => $type,
                    'key'  => ProgrammingEnum::PROGRAMMING_SAND_TABLE_KEY_MAPPING[$index] ?? 'programming',
                ];
            })->values()->toArray()
        ];
        $data[] = [
            'name'   => '网规等级',
            'select' => collect(ProgrammingEnum::GRADE_MAPPING)->map(function ($grade, $index) {
                return [
                    'name' => $grade,
                    'key'  => $index,
                ];
            })->values()->toArray()
        ];
        $data[] = [
            'name'   => '网规状态',
            'select' => collect(ProgrammingEnum::STATUS_MAPPING)->map(function ($status, $index) {
                return [
                    'name' => $status,
                    'key'  => $index,
                ];
            })->values()->toArray()
        ];
        $data[] = [
            'name'   => '互补品牌',
            'select' => collect(ProgrammingEnum::BRAND_SAND_TABLE_COMPLEMENTARY_PRODUCTS_MAPPING)->map(function ($product) {
                return [
                    'name' => $product,
                    'key'  => ProgrammingEnum::BRAND_SHOP_MAPPING[$product] ?? 'product',
                ];
            })->values()->toArray()
        ];
        $data[] = [
            'name'   => '竞品品牌',
            'select' => collect(ProgrammingEnum::BRAND_SAND_TABLE_COMPETITIVE_PRODUCTS_MAPPING)->map(function ($product) {
                return [
                    'name' => $product,
                    'key'  => ProgrammingEnum::BRAND_SHOP_MAPPING[$product] ?? 'product',
                ];
            })->values()->toArray()
        ];

        return $data;
    }


    /**
     * 获得城市下区县的中心经纬度
     * @return array
     */
    public static function getCenterDotByCity(): array
    {
        return Cache::remember('openShop:sandTable:districts:cache:center:dot', 864000, function () {
            ini_set('memory_limit', '512M');
            return CityTerritorialBoundaryModel::query()
                ->where('level', 'city')
                ->with(['cityTerritorialBoundaryRelByCity'])
                ->get()
                ->map(function (CityTerritorialBoundaryModel $cityTerritorialBoundaryModel) {
                    return [
                        'cityName'  => str_replace('城区', '', $cityTerritorialBoundaryModel->name),
                        'cityCode'  => $cityTerritorialBoundaryModel->adcode,
                        'centerLng' => $cityTerritorialBoundaryModel->centerLongitude,
                        'centerLat' => $cityTerritorialBoundaryModel->centerLatitude,
                        'district'  => $cityTerritorialBoundaryModel->cityTerritorialBoundaryRelByCity->map(function (CityTerritorialBoundaryModel $territorialBoundaryModel) {
                            return [
                                'districtName' => str_replace('城区', '', $territorialBoundaryModel->name),
                                'districtCode' => $territorialBoundaryModel->adcode,
                                'centerLng'    => $territorialBoundaryModel->centerLongitude,
                                'centerLat'    => $territorialBoundaryModel->centerLatitude,
                                'boundary'     => ''
                            ];
                        })
                    ];
                })->toArray();
        });

    }


    /**
     * 根据城市code获得该市下面所有的点位信息
     * @param int $cityCode
     * @return array
     */
    public static function getProgrammingDotByCity(int $cityCode): array
    {
        if (Cache::has('openShop:sandTable:districts:programming:dot:cityCode:' . $cityCode)) {
            return Cache::get('openShop:sandTable:districts:programming:dot:cityCode:' . $cityCode);
        }
        //通过城市code获得区
        $allDistrict = WangGuiCityByPower::getChinaDistrict();
        $cityInfo    = [];  //包含区的城市信息
        foreach ($allDistrict as $tempCity) {
            foreach ($tempCity['districts'] as $city) {
                if ($city['adcode'] == $cityCode) {
                    $cityInfo = $city;
                    break 2; // 跳出两层循环
                }
            }
        }

        return self::getCityDistrictDotInfo($cityInfo);
    }


    /**
     * 根据城市code获得该市下面所有的点位信息
     * @param int $cityCode
     * @return array
     */
    public static function getProgrammingDotByCityBurst(int $cityCode, int $page): array
    {
        if (Cache::has('openShop:sandTable:districts:burst' . $page . ':dot:cityCode:' . $cityCode)) {
            return [
                'page'  => $page,
                'value' => Cache::get('openShop:sandTable:districts:burst' . $page . ':dot:cityCode:' . $cityCode)
            ];
        }

        $jsonDot = json_encode(SandTableService::getProgrammingDotByCity($cityCode), JSON_UNESCAPED_UNICODE);
        $length = mb_strlen($jsonDot);
        $partLength = ceil($length / 3);
        // 使用substr提取字符串的每个部分
        $part[1] = substr($jsonDot, 0, $partLength);
        $part[2] = substr($jsonDot, $partLength, $partLength);
        $part[3] = substr($jsonDot, $partLength * 2);
        return [
            'page'  => $page,
            'value' => $part[$page]
        ];
    }


    /**
     * 根据城市code获得该市下面所有的点位信息 筛选
     * @param int $cityCode
     * @param int $adcode
     * @param $subType
     * @param $grade
     * @param $status
     * @param $pageNum
     * @param $pageSize
     * @return array
     */
    public static function getProgrammingDotByCitySearch(int $cityCode, int $adcode, $subType, $grade, $status, $pageNum, $pageSize): array
    {
        $subType   = explode(',', $subType);

        $wanggui = [];

        foreach ($subType as $k => $value) {
            if (in_array($value, SandTableEnum::SAND_TABLE_POLYMERIZE)) {
                $wanggui[] = $value;
                unset($subType[$k]);
            }
        }


        $paginator = SandTablePolymerizeDotInfoModel::query()
            ->where('cityCode', $cityCode)
            ->when($adcode, function ($query) use ($adcode){
                $query->where('adcode', $adcode);
            })
            ->where(function ($query) use ($subType, $grade, $status, $wanggui){
                $query->where(function ($q) use ($subType){
                    $q->whereIn('subType', array_values($subType));
                })
                    ->orWhere(function ($q) use ($grade, $status, $wanggui) {
                        $q->when(count($wanggui), function ($qq) use ($grade, $status, $wanggui) {
                            $qq->whereIn('subType', $wanggui)
                                ->when(strlen($grade), function ($qqq) use ($grade) {
                                    $qqq->whereIn('grade', explode(',', $grade));
                                })
                                ->when(strlen($status), function ($qqq) use ($status) {
                                    $qqq->whereIn('status', explode(',', $status));
                                });
                        });
                    });
            })
            ->orderByRaw("FIELD(type, 'communityProgramming', 'streetProgramming') ASC")
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $list = $paginator->map(function (SandTablePolymerizeDotInfoModel $sandTablePolymerizeDotInfoModel) {
            return [
                'id'       => $sandTablePolymerizeDotInfoModel->relationId,
                'name'     => $sandTablePolymerizeDotInfoModel->name,
                'lng'      => $sandTablePolymerizeDotInfoModel->lng,
                'lat'      => $sandTablePolymerizeDotInfoModel->lat,
                'type'     => $sandTablePolymerizeDotInfoModel->type,
                'key'      => $sandTablePolymerizeDotInfoModel->subType,
                'adcode'   => $sandTablePolymerizeDotInfoModel->adcode,
                'grade'    => $sandTablePolymerizeDotInfoModel->grade,
                'status'   => ProgrammingEnum::STATUS_SCORE_SAND_TABLE_MAPPING[(string)$sandTablePolymerizeDotInfoModel->status] ?? -1,
                'boundary' => json_decode($sandTablePolymerizeDotInfoModel->boundary, true),
            ];
        });

        return [
            'list'     => $list,
            'count'    => $paginator->total(),
            'pageNum'  => $pageNum,
            'pageSize' => $pageSize,
        ];
    }


    /**
     * 根据城市code获得该市下面所有的点位信息
     * @param int $cityCode
     * @return array
     */
    public static function getKfDotPolymerize(int $cityCode): array
    {
        if (Cache::has('openShop:sandTable:districts:polymerize:dot:cityCode:' . $cityCode)) {
            return Cache::get('openShop:sandTable:districts:polymerize:dot:cityCode:' . $cityCode);
        }
        $allDistrict = WangGuiCityByPower::getChinaDistrict();
        $cityInfo    = [];  //包含区的城市信息
        foreach ($allDistrict as $tempCity) {
            foreach ($tempCity['districts'] as $city) {
                if ($city['adcode'] == $cityCode) {
                    $cityInfo = $city;
                    break 2; // 跳出两层循环
                }
            }
        }
        //循环每个区获得区内点位信息
        $districtNameLists = array_column($cityInfo['districts'], 'name', 'adcode');
        $count      = [];
        foreach ($districtNameLists as $key => $value) {
            $count[$key] = 0;
        }
        $cityName          = mb_substr($cityInfo['name'], 0, 2);
        //门店信息
        try {
            $kfShop = GuanyuanDataService::newShopList();
        } catch (\Exception $exception) {
            $kfShop = [];
        }
        $totalCount = 0;
        foreach ($kfShop as $shop) {
            if (in_array($shop['区/县'], $districtNameLists) && in_array($shop['状态'], ProgrammingEnum::KF_SHOP_STATUS_SELECT_MAPPING) && mb_strpos($shop['门店所在市'], $cityName) !== false && $shop['门店经度'] && $shop['门店纬度']) {
                $totalCount++;
                isset($count[array_search($shop['区/县'], $districtNameLists)]) ? $count[array_search($shop['区/县'], $districtNameLists)]++ : ($count[array_search($shop['区/县'], $districtNameLists)] = 1);
            }
        }
        return [
            'totalCount'    => $totalCount,
            'districtCount' => collect($count)->map(function ($item, $code) {
                return [
                    'code'  => $code,
                    'count' => $item,
                ];
            })->values()->toArray()
        ];
    }


    /**
     * @param $type
     * @param $id
     * @param $rmsUserId
     * @return array
     * @throws GuzzleException
     * @throws \Exception
     */
    public static function getDotDetail($type, $id, $rmsUserId): array
    {
        $data               = [];
        $auditEffectiveTime = ConfigService::config('wanggui', 'auditEffectiveTime')['auditEffectiveTime'] ?? 0;
        //通过type和ID获得模型详情
        if ($type == SandTableEnum::KF_MODEL_SAND_TABLE) {
            $shopCode = str_pad($id, 4, '0', STR_PAD_LEFT);
            //夸父门店
            $wgNumber = 'KFZC' . str_pad($shopCode, 7, '0', STR_PAD_LEFT);

            $flowPeople   = 0;  //人流打分
            $openDistrict = 0;  //可开区域打分
            $fileList     = []; //图片List
            $status       = '待评估';
            $cover        = self::getDefaultCoverImage($wgNumber);  //默认封面图
            //获得评估日志
            $logModel  = OpenShopSiteLocationExamineLogModel::query()
                ->where('orderNo', $wgNumber)
                ->where('source', OpenShopSiteLocationExamineLogModel::SOURCE_OTHER_WG_AUDIT)
                ->orderBy('updatedAt')
                ->with(['resourceRelUsedToShow', 'wangguiSiteDistrictRel.resourceRel'])
                ->get();
            $body      = RmsUserService::getRmsUserInfoByUserIds($logModel->pluck('createdByUid')->toArray())['data'] ?? [];
            $userNames = array_column($body, 'username', 'id');
            $logs      = $logModel->map(function (OpenShopSiteLocationExamineLogModel $locationExamineLogModel) use (&$flowPeople, &$openDistrict, &$fileList, $rmsUserId, $auditEffectiveTime, &$status, $userNames, &$cover) {
                $file         = [];
                $flowPeople   = $locationExamineLogModel->flowOfPeopleScores;
                $openDistrict = $locationExamineLogModel->openPotential;
                $status       = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-';
                $locationExamineLogModel->resourceRelUsedToShow->each(function (ResourcesModel $resourcesModel) use (&$file, &$fileList, &$status, &$cover) {
                    if ((json_decode($resourcesModel->extra, true)['type'] ?? '') == 'image') {
                        $cover = picturePath($resourcesModel->url);
                    }
                    $file[$resourcesModel->name][] = ['url' => picturePath($resourcesModel->url), 'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')];
                    $fileList[]                    = ['url' => picturePath($resourcesModel->url), 'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')];
                });
                return array_merge([
                    'id'                 => $locationExamineLogModel->id,
                    'username'           => $userNames[$locationExamineLogModel->createdByUid] ?? '-',
                    'status'             => $locationExamineLogModel->status,
                    'openPotential'      => $locationExamineLogModel->openPotential,
                    'flowOfPeopleScores' => $locationExamineLogModel->flowOfPeopleScores,
                    'statusText'         => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-',
                    'createdAt'          => $locationExamineLogModel->updatedAt->format('Y-m-d H:i'),
                    'evaluateTime'       => $locationExamineLogModel->updatedAt->format('Y-m-d H:i'),
                    'content'            => $locationExamineLogModel->content,
                    'isUpdate'           => $locationExamineLogModel->createdByUid == $rmsUserId && time() < ($locationExamineLogModel->updatedAt->timestamp + $auditEffectiveTime * 3600),
                    'weather'            => DateTool::cnWeekOfDay($locationExamineLogModel->updatedAt->dayOfWeek) . ' ' . (json_decode($locationExamineLogModel->extra, true)['weather'] ?? ''),
                    'openDistrictList'   => $locationExamineLogModel->wangguiSiteDistrictRel->map(function (WangguiSiteDistrictModel $wangguiSiteDistrictModel) {
                        return [
                            'id'              => $wangguiSiteDistrictModel->id,
                            'name'            => $wangguiSiteDistrictModel->name,
                            'isEmptyShop'     => $wangguiSiteDistrictModel->isEmptyShop,
                            'isEmptyShopText' => WangguiSiteDistrictModel::IS_EMPTY_SHOP_MAPPING[$wangguiSiteDistrictModel->isEmptyShop] ?? '',
                            'file'            => $wangguiSiteDistrictModel->resourceRel->map(function (ResourcesModel $resourcesModel) {
                                return [
                                    'url'  => picturePath($resourcesModel->url),
                                    'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')
                                ];
                            })
                        ];
                    })->toArray(),
                ], $file);
            })->toArray();

            //            if (Cache::has('openShop:sandTable:kfShop:Cache:code:' . (int)$id)) {
            //                $data = Cache::get('openShop:sandTable:kfShop:Cache:code:' . (int)$id);
            //                $data = array_merge(
            //                    $data,
            //                    [
            //                        'score'    => [
            //                            '可开潜力值:' . $openDistrict,
            //                            '人流量:' . $flowPeople,
            //                        ],
            //                        'logs'     => $logs
            //                    ]
            //                );
            //            } else {


            $shop = GuanyuanSyncShopListModel::query()
                ->where('code', (int)$shopCode)
                ->first();

            if (null === $shop) {
                self::throwErr('获得观远门店数据失败');
            }

            // 获取折线图
            try {
                $shopId         = (int)optional(optional(OpenShopSignOrderModel::query()->where('shopCode', $id)->where('status', '!=', SignOrderEnum::ORDER_STATUS_NO)->with(['mainProcessRel'])->first())->mainProcessRel)->shopId;
                $showTimeTab    = 5;
                $showStartAt    = Carbon::now()->subDays(30)->startOfDay()->timestamp;
                $showEndAt      = Carbon::today()->startOfDay()->timestamp;
                $compareTimeTab = 4;
                $compareStartAt = Carbon::now()->subDays(60)->startOfDay()->timestamp;
                $compareEndAt   = Carbon::now()->subDays(30)->startOfDay()->timestamp;
                //获取折线图
                $res = (new RmsShopApi())->indexCharts($shopId, $showTimeTab, $showStartAt, $showEndAt, $compareTimeTab, $compareStartAt, $compareEndAt);
                if ($res['code'] == 1) {
                    $charts = $res['data'];
                } else {
                    $charts = [];
                }
            } catch (\Exception $exception) {
                $charts = [];
            }

            // 获得该门店最近的营业额
            $turnover = GuanyuanSyncShopBusinessModel::query()
                ->where('code', $shopCode)
                ->orderByDesc('date')
                ->first();

            $data = [
                'cover'         => $cover,
                'fileList'      => self::getFileList($fileList, $cover),
                'name'          => $shop->name,
                'label'         => collect([
                    $shop->status,
                    $shop->siteLocationType ?: null,
                    $shop->storeType ?: null,
                    $shop->cashierSystem ?: null
                ])->filter()->values()->toArray(),
                'takeawayScore' => '外卖评分: 美团' . (optional($turnover)->mtRating ?: '-') . ' | 饿了么' . (optional($turnover)->elmRating ?: '-'),
                'special'       => [
                    [
                        'name'  => '开业日期',
                        'value' => optional($turnover)->openBusinessDate ?: '-',
                    ],
                    [
                        'name'  => '已开业',
                        'value' => optional($turnover)->openingDurationMonth ? floor(optional($turnover)->openingDurationMonth) . '个月' : '-',
                    ]
                ],
                'grade'         => optional($turnover)->shopGrade ?: '',
                'lng'           => $shop->lng,
                'lat'           => $shop->lat,
                'province'      => $shop->province,
                'city'          => $shop->city,
                'district'      => $shop->district,
                'address'       => $shop->address,
                'status'        => $status,
                'type'          => 'kfShop',
                'key'           => ProgrammingEnum::KF_SHOP_SAND_TABLE_KEY_MAPPING[ProgrammingEnum::KF_SHOP_STATUS_REVERSE_MAPPING[$shop->status]] ?? 'kfShop',
                'score'         => [
                    '可开潜力值:' . $openDistrict,
                    '人流量:' . $flowPeople,
                ],
                'shopInfo'      => [
                    [
                        'name'  => '门店面积',
                        'value' => optional($turnover)->area ? (optional($turnover)->area . '㎡') : '-',
                    ], [
                        'name'  => '员工人数',
                        'value' => optional($turnover)->employeesNum ?: '-',
                    ], [
                        'name'  => '房租成本',
                        'value' => optional($turnover)->rent ? ('¥' . optional($turnover)->rent) : '-',
                    ], [
                        'name'  => '人力成本',
                        'value' => optional($turnover)->artificial ? ('¥' . optional($turnover)->artificial) : '-',
                    ]
                ],
                'phone'         => [],
                'charts'        => $charts,
                'logs'          => $logs
            ];

        } elseif ($type == 'business') {
            // 根据ID获得详情
            $businessModel = BusinessAoiModel::query()
                ->where('id', $id)
                ->first();

            if ($businessModel == null) {
                self::throwErr('获取商圈详情失败');
            }

            $data = [
                'cover'          => 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png',
                'name'           => $businessModel->name,
                'type'           => $type,
                'key'            => 'business',
                'status'         => '',
                'openPotential'  => '',
                'wgNumber'       => '',
                'label'          => [],
                'settleIn'       => '',
                'special'        => [],
                'grade'          => '',
                'lng'            => $businessModel->lng,
                'lat'            => $businessModel->lat,
                'province'       => $businessModel->province,
                'city'           => $businessModel->city,
                'district'       => $businessModel->district,
                'recommendFloor' => '',
                'address'        => '',
                'boundary'       => json_decode($businessModel->boundary, true)
            ];
        } else {
            //网规点位详情
            if (!isset(SandTableEnum::MODEL_SAND_TABLE_MAPPING[$type])) {
                self::throwErr('类型错误');
            }
            $model      = SandTableEnum::MODEL_SAND_TABLE_MAPPING[$type]::query();
            $modelQuery = $model->where('id', $id)->with(['logRel.resourceRelUsedToShow', 'logRel.resourceRelByCover'])->first();
            if ($modelQuery == null) {
                self::throwErr('获取网规点位详情失败');
            }
            $cover = self::getDefaultCoverImage($modelQuery->wgNumber);   //先获得地图图片
            optional($modelQuery->logRel)->each(function (OpenShopSiteLocationExamineLogModel $locationExamineLogModel) use (&$cover) {
                $locationExamineLogModel->resourceRelByCover->each(function (ResourcesModel $resourcesModel) use (&$cover) {
                    $fileType = json_decode($resourcesModel->extra, true)['type'] ?? '-';
                    if ($resourcesModel->name == ProgrammingEnum::WANGGUI_BUSINESS_DISTRIBUTION && $fileType == 'image') {
                        $cover = picturePath($resourcesModel->url);
                    }
                });
            });


            $fileList   = [];
            $flowPeople = 0;
            $status     = '待评估';
            $wgNumber   = $modelQuery->wgNumber;
            if ($type == 'product') {
                $logsModel  = OpenShopSiteLocationExamineLogModel::query()
                    ->where('source', OpenShopSiteLocationExamineLogModel::SOURCE_OTHER_WG_AUDIT)
                    ->orderBy('updatedAt', 'asc')
                    ->with(['resourceRelUsedToShow', 'wangguiSiteDistrictRel.resourceRel'])
                    ->where('orderNo', $wgNumber)
                    ->get();
                $logUserIds = (array)optional(optional($modelQuery->logRel)->pluck('createdByUid'))->toArray();
                $body       = RmsUserService::getRmsUserInfoByUserIds($logUserIds)['data'] ?? [];
                $userNames  = array_column($body, 'username', 'id');
                $logs       = $logsModel->map(function (OpenShopSiteLocationExamineLogModel $locationExamineLogModel) use (&$flowPeople, &$openDistrict, &$fileList, $rmsUserId, $auditEffectiveTime, &$status, $userNames) {
                    $file         = [];
                    $flowPeople   = $locationExamineLogModel->flowOfPeopleScores;
                    $openDistrict = $locationExamineLogModel->openPotential;
                    $status       = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-';
                    $locationExamineLogModel->resourceRelUsedToShow->each(function (ResourcesModel $resourcesModel) use (&$file, &$fileList) {
                        $file[$resourcesModel->name][] = ['url' => picturePath($resourcesModel->url), 'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')];
                        $fileList[]                    = ['url' => picturePath($resourcesModel->url), 'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')];
                    });
                    return array_merge([
                        'id'                 => $locationExamineLogModel->id,
                        'username'           => $userNames[$locationExamineLogModel->createdByUid] ?? '-',
                        'status'             => $locationExamineLogModel->status,
                        'openPotential'      => $locationExamineLogModel->openPotential,
                        'flowOfPeopleScores' => $locationExamineLogModel->flowOfPeopleScores,
                        'statusText'         => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-',
                        'createdAt'          => $locationExamineLogModel->updatedAt->format('Y-m-d H:i'),
                        'evaluateTime'       => $locationExamineLogModel->updatedAt->format('Y-m-d H:i'),
                        'content'            => $locationExamineLogModel->content,
                        'isUpdate'           => $locationExamineLogModel->createdByUid == $rmsUserId && time() < ($locationExamineLogModel->updatedAt->timestamp + $auditEffectiveTime * 3600),
                        'weather'            => DateTool::cnWeekOfDay($locationExamineLogModel->updatedAt->dayOfWeek) . ' ' . (json_decode($locationExamineLogModel->extra, true)['weather'] ?? ''),
                        'openDistrictList'   => $locationExamineLogModel->wangguiSiteDistrictRel->map(function (WangguiSiteDistrictModel $wangguiSiteDistrictModel) {
                            return [
                                'id'              => $wangguiSiteDistrictModel->id,
                                'name'            => $wangguiSiteDistrictModel->name,
                                'isEmptyShop'     => $wangguiSiteDistrictModel->isEmptyShop,
                                'isEmptyShopText' => WangguiSiteDistrictModel::IS_EMPTY_SHOP_MAPPING[$wangguiSiteDistrictModel->isEmptyShop] ?? '',
                                'file'            => $wangguiSiteDistrictModel->resourceRel->map(function (ResourcesModel $resourcesModel) {
                                    return [
                                        'url'  => picturePath($resourcesModel->url),
                                        'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')
                                    ];
                                })
                            ];
                        })
                    ], $file);
                })->toArray();
            } else {
                $logUserIds = (array)optional(optional($modelQuery->logRel)->pluck('createdByUid'))->toArray();
                $body       = RmsUserService::getRmsUserInfoByUserIds($logUserIds)['data'] ?? [];
                $userNames  = array_column($body, 'username', 'id');
                $logs       = (array)optional(
                    optional($modelQuery->logRel)->map(function (OpenShopSiteLocationExamineLogModel $locationExamineLogModel) use ($rmsUserId, $userNames, $auditEffectiveTime, $cover, &$fileList, &$flowPeople, &$status) {
                        $file       = [];
                        $flowPeople = $locationExamineLogModel->flowOfPeopleScores;
                        $status     = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-';
                        $locationExamineLogModel->resourceRelUsedToShow->each(function (ResourcesModel $resourcesModel) use (&$file, &$fileList) {
                            $file[$resourcesModel->name][] = ['url' => picturePath($resourcesModel->url), 'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')];
                            $fileList[]                    = ['url' => picturePath($resourcesModel->url), 'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')];
                        });
                        return array_merge([
                            'id'                 => $locationExamineLogModel->id,
                            'username'           => $userNames[$locationExamineLogModel->createdByUid] ?? '-',
                            'status'             => $locationExamineLogModel->status,
                            'openPotential'      => $locationExamineLogModel->openPotential,
                            'flowOfPeopleScores' => $locationExamineLogModel->flowOfPeopleScores,
                            'statusText'         => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-',
                            'createdAt'          => $locationExamineLogModel->updatedAt->format('Y-m-d H:i'),
                            'evaluateTime'       => $locationExamineLogModel->updatedAt->format('Y-m-d H:i'),
                            'content'            => $locationExamineLogModel->content,
                            'isUpdate'           => $locationExamineLogModel->createdByUid == $rmsUserId && time() < ($locationExamineLogModel->updatedAt->timestamp + $auditEffectiveTime * 3600),
                            'weather'            => DateTool::cnWeekOfDay($locationExamineLogModel->updatedAt->dayOfWeek) . ' ' . (json_decode($locationExamineLogModel->extra, true)['weather'] ?? ''),
                            'openDistrictList'   => $locationExamineLogModel->wangguiSiteDistrictRel->map(function (WangguiSiteDistrictModel $wangguiSiteDistrictModel) {
                                return [
                                    'id'              => $wangguiSiteDistrictModel->id,
                                    'name'            => $wangguiSiteDistrictModel->name,
                                    'isEmptyShop'     => $wangguiSiteDistrictModel->isEmptyShop,
                                    'isEmptyShopText' => WangguiSiteDistrictModel::IS_EMPTY_SHOP_MAPPING[$wangguiSiteDistrictModel->isEmptyShop] ?? '',
                                    'file'            => $wangguiSiteDistrictModel->resourceRel->map(function (ResourcesModel $resourcesModel) {
                                        return [
                                            'url'  => picturePath($resourcesModel->url),
                                            'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')
                                        ];
                                    })
                                ];
                            })
                        ], $file);
                    })
                )->toArray();
            }

            switch ($type) {
                case 'mallProgramming':
                    $label   = array_merge(
                        (mb_strlen($modelQuery->topList) ? [$modelQuery->topList] : [])
                    );
                    $special = [
                        [
                            'name'  => '店铺总数',
                            'value' => $modelQuery->shopTotalCount,
                        ], [
                            'name'  => '美食店铺占比',
                            'value' => $modelQuery->foodRatio ? ($modelQuery->foodRatio * 100 . '%') : 0,
                        ], [
                            'name'  => '夸父门店数',
                            'value' => $modelQuery->shopNum,
                        ]
                    ];
                    break;
                case 'streetProgramming':
                case 'communityProgramming':
                case 'parkProgramming':
                    $label   = [];
                    $special = [
                        [
                            'name'  => '夸父门店数',
                            'value' => $modelQuery->shopNum,
                        ]
                    ];
                    break;
                case 'townProgramming':
                    $label   = array_merge(
                        ($modelQuery->shopCountRank ? ['商超数排名第' . $modelQuery->shopCountRank] : []),
                        ($modelQuery->qianqiangTownRank ? ['千强镇第' . $modelQuery->qianqiangTownRank . '名'] : [])
                    );
                    $special = [
                        [
                            'name'  => '人口密度',
                            'value' => round($modelQuery->peopleDensity, 1),
                        ], [
                            'name'  => '人口密度排名',
                            'value' => $modelQuery->peopleDensityRank,
                        ], [
                            'name'  => '夸父门店数',
                            'value' => $modelQuery->shopNum,
                        ]
                    ];
                    break;
                case 'schoolProgramming':
                    $label   = array_merge(
                        ($modelQuery->doubleFirstClass == '是' ? ['双一流'] : []),
                        ($modelQuery->project985 == '是' ? ['985'] : []),
                        ($modelQuery->project211 == '是' ? ['211'] : []),
                        ($modelQuery->strongBasis == '是' ? ['强基'] : [])
                    );
                    $special = [
                        [
                            'name'  => '院校类型',
                            'value' => $modelQuery->schoolType,
                        ], [
                            'name'  => '面积',
                            'value' => $modelQuery->space . '亩',
                        ], [
                            'name'  => '夸父门店数',
                            'value' => $modelQuery->shopNum,
                        ]
                    ];
                    break;
                case 'product':
                    $label   = [];
                    $special = [
                        [
                            'name'  => '开业时间',
                            'value' => $modelQuery->openingTime ?: '-',
                        ], [
                            'name'  => '营业时间',
                            'value' => $modelQuery->openingTime ? Carbon::parse($modelQuery->openingTime)->diff(Carbon::now())->format('%y年%m个月') : '-'
                        ]
                    ];
                    $key     = ProgrammingEnum::BRAND_SHOP_MAPPING[$modelQuery->brand] ?? 'product';
                    break;
                default:
                    $label   = [];
                    $special = [];
            }



            $data = [
                'cover'    => $cover ?: 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png',
                'fileList' => self::getFileList($fileList, $cover),
                'name'     => $modelQuery->nameText,
                'isMall'   => $type == 'mallProgramming',
                'type'     => $type,
                'key'      => isset($key) ?: (string)array_search(get_class($modelQuery), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                'status'   => $status,
                'wgNumber' => $modelQuery->wgNumber,
                'label'    => $label,
                'settleIn' => $modelQuery->settle ? '已入驻' : '',
                'special'  => $special,
                'grade'    => ProgrammingEnum::GRADE_MAPPING[$modelQuery->grade] ?? '',
                'lng'      => $modelQuery->lng,
                'lat'      => $modelQuery->lat,
                'province' => $modelQuery->province,
                'city'     => $modelQuery->city,
                'district' => $modelQuery->district,
                'address'  => $modelQuery->address,
                'recommendFloor'  => $modelQuery->recommendFloor ?: '',
                'score'    => [
                    '可开潜力值:' . $modelQuery->status,
                    '人流量:' . $flowPeople,
                ],
                'phone'    => $modelQuery->phone ? explode('|', $modelQuery->phone) : [],
                'logs'     => $logs
            ];
        }
        //获得外卖预估
        $distance = 3;  //默认3km
        // 外卖预估数据
        if (!$data['lng'] || !$data['lat']) {
            $takeOutInfo = [
                'elmSalesVolume'                   => '',
                'takeOutDoubleSalesVolume'         => '',
                'takeOutDoubleSalesVolumeReceived' => '',
                'mtSalesVolume'                    => '',
            ];
        } else {
            $takeOutData = (new WaiMaiAnalysisService())
                ->setLngLat($data['lng'], $data['lat'], $distance);
            $estimate    = $takeOutData->calcEstimateData();
            $takeOutInfo = [
                'takeOutDoubleSalesVolume'         => (int)(array_sum($estimate['estimate']) * 0.8) . '~' . (int)(array_sum($estimate['estimate']) * 1.2),
                'takeOutDoubleSalesVolumeReceived' => ((int)(array_sum($estimate['estimate']) * 0.8) * 30) . '~' . ((int)(array_sum($estimate['estimate']) * 1.2) * 30),
                'mtSalesVolume'                    => (int)($estimate['estimate']['mt'] * 0.8) . '~' . (int)($estimate['estimate']['mt'] * 1.2),
                'elmSalesVolume'                   => (int)($estimate['estimate']['elm'] * 0.8) . '~' . (int)($estimate['estimate']['elm'] * 1.2),
            ];
        }
        $data['takeOutInfo'] = $takeOutInfo;

        return $data;
    }

    /**
     * @param $type
     * @param $id
     * @param $rmsUserId
     * @return array
     * @throws GuzzleException
     */
    public static function getDotCardInfo($type, $id, $rmsUserId): array
    {
        //通过type和ID获得模型详情
        if ($type == SandTableEnum::KF_MODEL_SAND_TABLE) {
            if (Cache::has('openShop:sandTable:kfShop:Cache:code:' . (int)$id)) {
                return Cache::get('openShop:sandTable:kfShop:Cache:code:' . (int)$id);
            }
            //获得观远的门店数据
            $shopCode         = str_pad($id, 4, '0', STR_PAD_LEFT);
            try {
                GuanyuanDataService::setTimeOut(10);
                $guanyuanDataList = GuanyuanDataService::getShopBusinessInfoByCode([$shopCode]);
            } catch (\Exception $exception) {
                throw new ResponseHttpException(504, null, '获取门店详情超时,请稍后再试');
            }
            $maxDate          = 0;
            $maxItem          = [];
            foreach ($guanyuanDataList as $guanyuanData) {
                $date = strtotime($guanyuanData['date']);
                if ($date > $maxDate) {
                    $maxDate = $date;
                    $maxItem = $guanyuanData;
                }
            }
            $data = self::getKfShopCardInfo($shopCode, $maxItem);
        } elseif ($type == 'business') {
            // 根据ID获得详情
            $businessModel = BusinessAoiModel::query()
                ->where('id', $id)
                ->first();

            if ($businessModel == null) {
                self::throwErr('获取商圈详情失败');
            }

            $data = [
                'cover'          => 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png',
                'name'           => $businessModel->name,
                'type'           => $type,
                'key'            => 'business',
                'status'         => '',
                'openPotential'  => '',
                'wgNumber'       => '',
                'label'          => [],
                'settleIn'       => '',
                'special'        => [],
                'grade'          => '',
                'lng'            => $businessModel->lng,
                'lat'            => $businessModel->lat,
                'province'       => $businessModel->province,
                'city'           => $businessModel->city,
                'district'       => $businessModel->district,
                'recommendFloor' => '',  //推荐楼层
                'address'        => '',
                'boundary'       => json_decode($businessModel->boundary, true)
            ];
        } else {
            //点位
            if (!isset(SandTableEnum::MODEL_SAND_TABLE_MAPPING[$type])) {
                self::throwErr('类型错误');
            }
            $model      = SandTableEnum::MODEL_SAND_TABLE_MAPPING[$type]::query();
            $modelQuery = $model->where('id', $id)->with(['logRel.resourceRelUsedToShow', 'logRel.resourceRelByCover', 'resourceWithMapRel'])->first();
            if ($modelQuery == null) {
                self::throwErr('获取网规点位详情失败');
            }
            $cover = self::getDefaultCoverImage($modelQuery->wgNumber);   //先获得地图图片
            optional($modelQuery->logRel)->each(function (OpenShopSiteLocationExamineLogModel $locationExamineLogModel) use (&$cover) {
                $locationExamineLogModel->resourceRelByCover->each(function (ResourcesModel $resourcesModel) use (&$cover) {
                    $fileType = json_decode($resourcesModel->extra, true)['type'] ?? '-';
                    if ($resourcesModel->name == ProgrammingEnum::WANGGUI_BUSINESS_DISTRIBUTION && $fileType == 'image') {
                        $cover = picturePath($resourcesModel->url);
                    }
                });
            });
            $status   = '待评估';
            $wgNumber = $modelQuery->wgNumber;
            if ($type == 'product') {
                OpenShopSiteLocationExamineLogModel::query()
                    ->where('source', OpenShopSiteLocationExamineLogModel::SOURCE_OTHER_WG_AUDIT)
                    ->orderBy('updatedAt', 'asc')
                    ->with(['resourceRelUsedToShow', 'wangguiSiteDistrictRel.resourceRel'])
                    ->where('orderNo', $wgNumber)
                    ->get()
                    ->each(function (OpenShopSiteLocationExamineLogModel $locationExamineLogModel) use (&$status) {
                        $status = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-';
                    });
            } else {
                optional(
                    optional($modelQuery->logRel)->each(function (OpenShopSiteLocationExamineLogModel $locationExamineLogModel) use (&$status) {
                        $status = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-';
                    })
                );
            }

            switch ($type) {
                case 'mallProgramming':
                    $label   = array_merge(
                        (mb_strlen($modelQuery->topList) ? [$modelQuery->topList] : [])
                    );
                    $special = [
                        [
                            'name'  => '店铺总数',
                            'value' => $modelQuery->shopTotalCount,
                        ], [
                            'name'  => '美食店铺占比',
                            'value' => $modelQuery->foodRatio ? ($modelQuery->foodRatio * 100 . '%') : 0,
                        ], [
                            'name'  => '夸父门店数',
                            'value' => $modelQuery->shopNum,
                        ]
                    ];
                    break;
                case 'streetProgramming':
                case 'communityProgramming':
                case 'parkProgramming':
                    $label   = [];
                    $special = [
                        [
                            'name'  => '夸父门店数',
                            'value' => $modelQuery->shopNum,
                        ]
                    ];
                    break;
                case 'townProgramming':
                    $label   = array_merge(
                        ($modelQuery->shopCountRank ? ['商超数排名第' . $modelQuery->shopCountRank] : []),
                        ($modelQuery->qianqiangTownRank ? ['千强镇第' . $modelQuery->qianqiangTownRank . '名'] : [])
                    );
                    $special = [
                        [
                            'name'  => '人口密度',
                            'value' => round($modelQuery->peopleDensity, 1),
                        ], [
                            'name'  => '人口密度排名',
                            'value' => $modelQuery->peopleDensityRank,
                        ], [
                            'name'  => '夸父门店数',
                            'value' => $modelQuery->shopNum,
                        ]
                    ];
                    break;
                case 'schoolProgramming':
                    $label   = array_merge(
                        ($modelQuery->doubleFirstClass == '是' ? ['双一流'] : []),
                        ($modelQuery->project985 == '是' ? ['985'] : []),
                        ($modelQuery->project211 == '是' ? ['211'] : []),
                        ($modelQuery->strongBasis == '是' ? ['强基'] : [])
                    );
                    $special = [
                        [
                            'name'  => '院校类型',
                            'value' => $modelQuery->schoolType,
                        ], [
                            'name'  => '面积',
                            'value' => $modelQuery->space . '亩',
                        ], [
                            'name'  => '夸父门店数',
                            'value' => $modelQuery->shopNum,
                        ]
                    ];
                    break;
                case 'product':
                    $label   = [];
                    $special = [
                        [
                            'name'  => '开业时间',
                            'value' => $modelQuery->openingTime ?: '-',
                        ], [
                            'name'  => '营业时间',
                            'value' => $modelQuery->openingTime ? Carbon::parse($modelQuery->openingTime)->diff(Carbon::now())->format('%y年%m个月') : '-'
                        ]
                    ];
                    $key     = ProgrammingEnum::BRAND_SHOP_MAPPING[$modelQuery->brand] ?? 'product';
                    break;
                default:
                    $label   = [];
                    $special = [];
            }

            $data = [
                'cover'          => $cover ?: 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png',
                'name'           => $modelQuery->nameText,
                'type'           => $type,
                'key'            => $key ?? (string)array_search(get_class($modelQuery), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                'status'         => $status,
                'openPotential'  => $modelQuery->status,
                'wgNumber'       => $modelQuery->wgNumber,
                'label'          => $label,
                'settleIn'       => $modelQuery->settle ? '已入驻' : '',
                'special'        => $special,
                'grade'          => ProgrammingEnum::GRADE_MAPPING[$modelQuery->grade] ?? '',
                'lng'            => $modelQuery->lng,
                'lat'            => $modelQuery->lat,
                'province'       => $modelQuery->province,
                'city'           => $modelQuery->city,
                'district'       => $modelQuery->district,
                'recommendFloor' => $modelQuery->recommendFloor ?: '',  //推荐楼层
                'address'        => $modelQuery->address,
                'boundary'       => $modelQuery->coords ? collect(json_decode($modelQuery->coords, true))->map(function ($item) {
                    return [
                        'lat' => $item[1],
                        'lng' => $item[0],
                    ];
                }) : []
            ];
        }
        return $data;
    }

    /**
     * 点位搜索
     * @param string $type
     * @param $name
     * @param $adcode
     * @param $pageNum
     * @param $pageSize
     * @return array
     */
    public static function dotSearch(string $type, $name, $adcode, $pageNum, $pageSize): array
    {
        $amapKey  = WangGuiCityByPower::getRandomAmapKey();
        $response = Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
            ->get(config('area.getAreaByName'), [
                'keywords'    => $adcode,
                'subdistrict' => 0,
                'key'         => $amapKey,
            ])
            ->json();
        if ($response['status'] != 1) {
            self::throwErr('城市code获取错误,请刷新重试');
        }
        //获得一些条件
        $level = $response['districts'][0]['level'] ?? 0;
        $value = mb_substr($response['districts'][0]['name'] ?? '', 0, 2);
        $list  = [];
        switch ($type) {
            case 'amap':
                if (empty($name) && empty($value)) {
                    self::throwErr('获取位置失败 请重新进入尝试');
                } elseif (empty($name) && !empty($value)) {
                    $name = $value;
                }
                $response = Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
                    ->get(config('area.getAreaListByName'), [
                        'key'        => $amapKey,
                        'keywords'   => $name,
                        'page_size'  => $pageSize,
                        'page_num'   => $pageNum,
                        'city_limit' => true,
                        'region'     => $adcode,
                    ])
                    ->json();
                if ($response['status'] != 1) {
                    self::throwErr('获取结果失败,请重新获取');
                }
                $list = [
                    'list' => collect($response['pois'])->map(function ($dot) {
                        $position = explode(',', $dot['location']);
                        return [
                            'name'    => $dot['name'],
                            'address' => $dot['address'],
                            'lat'     => $position[1],
                            'lng'     => $position[0],
                            'type'    => 'amap',
                            'key'     => 'amap',
                            'id'      => 0,
                        ];
                    })
                ];
                break;
            case 'kfShop':
                try {
                    $kfShop  = GuanyuanDataService::newShopList();
                } catch (\Exception $exception) {
                    $kfShop = [];
                }
                $tempList = [];
                if (empty($name)) {
                    $name = '夸父';
                }
                collect($kfShop)->each(function ($shop) use (&$tempList, $name, $level, $value) {
                    switch ($level) {
                        case "city":
                            if (mb_strpos($shop['门店所在市'], $value) !== false && (mb_strpos($shop['门店名称'], $name) !== false || mb_strpos($shop['店铺地址'], $name)) && $shop['门店经度'] && $shop['门店纬度']) {
                                $tempList[] = [
                                    'name'    => $shop['状态'] . '-' . $shop['门店名称'],
                                    'address' => $shop['店铺地址'],
                                    'lat'     => $shop['门店纬度'],
                                    'lng'     => $shop['门店经度'],
                                    'key'     => ProgrammingEnum::KF_SHOP_SAND_TABLE_KEY_MAPPING[ProgrammingEnum::KF_SHOP_STATUS_REVERSE_MAPPING[$shop['状态']] ?? 0] ?? 'kfShop',
                                    'type'    => SandTableEnum::KF_MODEL_SAND_TABLE,
                                    'id'      => $shop['铺位号'],
                                ];
                            }
                            break;
                        case "district":
                            if (mb_strpos($shop['区/县'], $value) !== false && (mb_strpos($shop['门店名称'], $name) !== false || mb_strpos($shop['店铺地址'], $name)) && $shop['门店经度'] && $shop['门店纬度']) {
                                $tempList[] = [
                                    'name'    => $shop['状态'] . '-' . $shop['门店名称'],
                                    'address' => $shop['店铺地址'],
                                    'lat'     => $shop['门店纬度'],
                                    'lng'     => $shop['门店经度'],
                                    'key'     => ProgrammingEnum::KF_SHOP_SAND_TABLE_KEY_MAPPING[ProgrammingEnum::KF_SHOP_STATUS_REVERSE_MAPPING[$shop['状态']] ?? 0] ?? 'kfShop',
                                    'type'    => SandTableEnum::KF_MODEL_SAND_TABLE,
                                    'id'      => $shop['铺位号'],
                                ];
                            }
                            break;
                    }
                });
                $list = [
                    'count'    => count($tempList),
                    'pageNum'  => $pageNum,
                    'pageSize' => $pageSize,
                    'list'     => $tempList
                ];
                break;
            case 'mallProgramming':
                $paginate = SiteLocationMallModel::query()
                    ->where(function ($query) use ($name) {
                        $query->where('mallName', 'like', "%$name%")
                            ->orWhere('address', 'like', "%$name%");
                    })
                    ->where($level, 'like', "%$value%")
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
                $list     = [
                    'count'    => $paginate->total(),
                    'pageNum'  => $pageNum,
                    'pageSize' => $pageSize,
                    'list'     => collect($paginate->items())->map(function (SiteLocationMallModel $siteLocationMallModel) {
                        return [
                            'name'    => $siteLocationMallModel->mallName,
                            'address' => $siteLocationMallModel->address,
                            'lat'     => $siteLocationMallModel->lat,
                            'lng'     => $siteLocationMallModel->lng,
                            'grade'   => $siteLocationMallModel->grade,
                            'type'    => (string)array_search(get_class($siteLocationMallModel), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                            'key'     => (string)array_search(get_class($siteLocationMallModel), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                            'id'      => $siteLocationMallModel->id,
                        ];
                    })->values()->toArray(),
                ];
                break;
            case 'streetProgramming':
                $paginate = MapNationalStreetModel::query()
                    ->where(function ($query) use ($name) {
                        $query->where('name', 'like', "%$name%")
                            ->orWhere('address', 'like', "%$name%");
                    })
                    ->where($level, 'like', "%$value%")
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
                $list     = [
                    'count'    => $paginate->total(),
                    'pageNum'  => $pageNum,
                    'pageSize' => $pageSize,
                    'list'     => collect($paginate->items())->map(function (MapNationalStreetModel $mapNationalStreetModel) {
                        return [
                            'name'    => $mapNationalStreetModel->name,
                            'address' => $mapNationalStreetModel->address,
                            'lat'     => $mapNationalStreetModel->lat,
                            'lng'     => $mapNationalStreetModel->lng,
                            'grade'   => $mapNationalStreetModel->grade,
                            'type'    => (string)array_search(get_class($mapNationalStreetModel), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                            'key'     => (string)array_search(get_class($mapNationalStreetModel), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                            'id'      => $mapNationalStreetModel->id,
                        ];
                    })->values()->toArray(),
                ];
                break;
            case 'communityProgramming':
                $paginate = MapNationalCommunityModel::query()
                    ->where(function ($query) use ($name) {
                        $query->where('name', 'like', "%$name%")
                            ->orWhere('address', 'like', "%$name%");
                    })
                    ->where($level, 'like', "%$value%")
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
                $list     = [
                    'count'    => $paginate->total(),
                    'pageNum'  => $pageNum,
                    'pageSize' => $pageSize,
                    'list'     => collect($paginate->items())->map(function (MapNationalCommunityModel $mapNationalCommunityModel) {
                        return [
                            'name'    => $mapNationalCommunityModel->name,
                            'address' => $mapNationalCommunityModel->address,
                            'lat'     => $mapNationalCommunityModel->lat,
                            'lng'     => $mapNationalCommunityModel->lng,
                            'grade'   => $mapNationalCommunityModel->grade,
                            'type'    => (string)array_search(get_class($mapNationalCommunityModel), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                            'key'     => (string)array_search(get_class($mapNationalCommunityModel), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                            'id'      => $mapNationalCommunityModel->id,
                        ];
                    })->values()->toArray(),
                ];
                break;
            case 'townProgramming':
                $paginate = MapTownshipPlanAreaModel::query()
                    ->where(function ($query) use ($name) {
                        $query->where('area', 'like', "%$name%")
                            ->orWhere('address', 'like', "%$name%");
                    })
                    ->where($level, 'like', "%$value%")
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
                $list     = [
                    'count'    => $paginate->total(),
                    'pageNum'  => $pageNum,
                    'pageSize' => $pageSize,
                    'list'     => collect($paginate->items())->map(function (MapTownshipPlanAreaModel $mapTownshipPlanAreaModel) {
                        return [
                            'name'    => $mapTownshipPlanAreaModel->area,
                            'address' => $mapTownshipPlanAreaModel->address,
                            'lat'     => $mapTownshipPlanAreaModel->lat,
                            'lng'     => $mapTownshipPlanAreaModel->lng,
                            'grade'   => $mapTownshipPlanAreaModel->grade,
                            'type'    => (string)array_search(get_class($mapTownshipPlanAreaModel), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                            'key'     => (string)array_search(get_class($mapTownshipPlanAreaModel), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                            'id'      => $mapTownshipPlanAreaModel->id,
                        ];
                    })->values()->toArray(),
                ];
                break;
            case 'schoolProgramming':
                $paginate = MapNationalUniversitiesModel::query()
                    ->where(function ($query) use ($name) {
                        $query->where('name', 'like', "%$name%")
                            ->orWhere('address', 'like', "%$name%");
                    })
                    ->where($level, 'like', "%$value%")
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
                $list     = [
                    'count'    => $paginate->total(),
                    'pageNum'  => $pageNum,
                    'pageSize' => $pageSize,
                    'list'     => collect($paginate->items())->map(function (MapNationalUniversitiesModel $mapNationalUniversitiesModel) {
                        return [
                            'name'    => $mapNationalUniversitiesModel->name,
                            'address' => $mapNationalUniversitiesModel->address,
                            'lat'     => $mapNationalUniversitiesModel->lat,
                            'lng'     => $mapNationalUniversitiesModel->lng,
                            'grade'   => $mapNationalUniversitiesModel->grade,
                            'type'    => (string)array_search(get_class($mapNationalUniversitiesModel), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                            'key'     => (string)array_search(get_class($mapNationalUniversitiesModel), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                            'id'      => $mapNationalUniversitiesModel->id,
                        ];
                    })->values()->toArray(),
                ];
                break;
            case 'parkProgramming':
                $paginate = MapNationalIndustrialParkModel::query()
                    ->where('name', 'like', "%$name%")
                    ->where($level, 'like', "%$value%")
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
                $list     = [
                    'count'    => $paginate->total(),
                    'pageNum'  => $pageNum,
                    'pageSize' => $pageSize,
                    'list'     => collect($paginate->items())->map(function (MapNationalIndustrialParkModel $mapNationalIndustrialParkModel) {
                        return [
                            'name'    => $mapNationalIndustrialParkModel->name,
                            'address' => $mapNationalIndustrialParkModel->name,
                            'lat'     => $mapNationalIndustrialParkModel->lat,
                            'lng'     => $mapNationalIndustrialParkModel->lng,
                            'grade'   => $mapNationalIndustrialParkModel->grade,
                            'type'    => (string)array_search(get_class($mapNationalIndustrialParkModel), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                            'key'     => (string)array_search(get_class($mapNationalIndustrialParkModel), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                            'id'      => $mapNationalIndustrialParkModel->id,
                        ];
                    })->values()->toArray(),
                ];
                break;
            case 'product':
                $paginate = MapNationalBrandShopModel::query()
                    ->where(function ($query) use ($name) {
                        $query->where('name', 'like', "%$name%")
                            ->orWhere('address', 'like', "%$name%");
                    })
                    ->where($level, 'like', "%$value%")
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
                $list     = [
                    'count'    => $paginate->total(),
                    'pageNum'  => $pageNum,
                    'pageSize' => $pageSize,
                    'list'     => collect($paginate->items())->map(function (MapNationalBrandShopModel $mapNationalBrandShopModel) {
                        return [
                            'name'    => $mapNationalBrandShopModel->name,
                            'address' => $mapNationalBrandShopModel->address,
                            'lat'     => $mapNationalBrandShopModel->lat,
                            'lng'     => $mapNationalBrandShopModel->lng,
                            'type'    => (string)array_search(get_class($mapNationalBrandShopModel), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                            'id'      => $mapNationalBrandShopModel->id,
                            'key'     => ProgrammingEnum::BRAND_SHOP_MAPPING[$mapNationalBrandShopModel->brand] ?? 'product',
                        ];
                    })->values()->toArray(),
                ];
                break;
            case 'competitiveProduct':
                $paginate = MapNationalBrandShopModel::query()
                    ->where('type', MapNationalBrandShopModel::COMPETITIVE_PRODUCTS)
                    ->where(function ($query) use ($name) {
                        $query->where('name', 'like', "%$name%")
                            ->orWhere('address', 'like', "%$name%");
                    })
                    ->where($level, 'like', "%$value%")
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
                $list     = [
                    'count'    => $paginate->total(),
                    'pageNum'  => $pageNum,
                    'pageSize' => $pageSize,
                    'list'     => collect($paginate->items())->map(function (MapNationalBrandShopModel $mapNationalBrandShopModel) {
                        return [
                            'name'    => $mapNationalBrandShopModel->name,
                            'address' => $mapNationalBrandShopModel->address,
                            'lat'     => $mapNationalBrandShopModel->lat,
                            'lng'     => $mapNationalBrandShopModel->lng,
                            'type'    => (string)array_search(get_class($mapNationalBrandShopModel), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                            'id'      => $mapNationalBrandShopModel->id,
                            'key'     => ProgrammingEnum::BRAND_SHOP_MAPPING[$mapNationalBrandShopModel->brand] ?? 'product',
                        ];
                    })->values()->toArray(),
                ];
                break;
            case 'complementaryProduct':
                $paginate = MapNationalBrandShopModel::query()
                    ->where('type', MapNationalBrandShopModel::COMPLEMENTARY_PRODUCTS)
                    ->where(function ($query) use ($name) {
                        $query->where('name', 'like', "%$name%")
                            ->orWhere('address', 'like', "%$name%");
                    })
                    ->where($level, 'like', "%$value%")
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
                $list     = [
                    'count'    => $paginate->total(),
                    'pageNum'  => $pageNum,
                    'pageSize' => $pageSize,
                    'list'     => collect($paginate->items())->map(function (MapNationalBrandShopModel $mapNationalBrandShopModel) {
                        return [
                            'name'    => $mapNationalBrandShopModel->name,
                            'address' => $mapNationalBrandShopModel->address,
                            'lat'     => $mapNationalBrandShopModel->lat,
                            'lng'     => $mapNationalBrandShopModel->lng,
                            'type'    => (string)array_search(get_class($mapNationalBrandShopModel), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                            'id'      => $mapNationalBrandShopModel->id,
                            'key'     => ProgrammingEnum::BRAND_SHOP_MAPPING[$mapNationalBrandShopModel->brand] ?? 'product',
                        ];
                    })->values()->toArray(),
                ];
                break;
            case 'business':
                $specialCityCodeJson = (string)ConfigModel::query()
                    ->where('module', 'businessAoi')
                    ->where('name', 'cityCodeConvert')
                    ->value('value');
                $specialCityCodeArr  = json_decode($specialCityCodeJson, true);
                $cityCode = $specialCityCodeArr[$adcode] ?? $adcode;
                $paginate = BusinessAoiModel::query()
                    ->where('cityCode', $cityCode)
                    ->where('level', 'bizcircle')
                    ->where(function ($query) use ($name) {
                        $query->where('name', 'like', "%$name%");
                    })
                    ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
                $list     = [
                    'count'    => $paginate->total(),
                    'pageNum'  => $pageNum,
                    'pageSize' => $pageSize,
                    'list'     => collect($paginate->items())->map(function (BusinessAoiModel $businessAoiModel) {
                        return [
                            'name'    => $businessAoiModel->name,
                            'address' => $businessAoiModel->province . $businessAoiModel->city. $businessAoiModel->district,
                            'lat'     => $businessAoiModel->lat,
                            'lng'     => $businessAoiModel->lng,
                            'grade'   => '',
                            'type'    => 'business',
                            'key'     => '',
                            'id'      => $businessAoiModel->id,
                        ];
                    })->values()->toArray()
                ];
                break;
            default:
                self::throwErr('未知搜索类型,请联系相关负责人');
        }
        return $list;

    }

    public static function getAreaListByKeyword($keyword) {}

    public static function dotEvaluate(
        int     $id,
        string  $type,
        float   $openPotential,
        ?string $content,
        float   $flowScore,
        array   $flowFile,
        array   $businessFile,
        array   $customerGroupType,
        array   $passengerFlowDrive,
        array   $canOpenArea,
        array   $overallMovingLine,
        array   $takeawayEvaluation,
        array   $floorGuidance,
        string  $rmsUserName,
        int     $rmsUserId,
                $evaluateId,
        string  $evaluateTime
    )
    {

        if ($type == SandTableEnum::KF_MODEL_SAND_TABLE) {
            $orderNo = 'KFZC' . str_pad($id, 7, '0', STR_PAD_LEFT);
            //门店信息
            try {
                $shopInfo   = GuanyuanDataService::newShopList($id)[0] ?? [];
            } catch (\Exception $exception) {
                $shopInfo = [];
            }
            if (empty($shopInfo)) {
                self::throwErr('获取门店信息失败');
            }
            $lat        = $shopInfo['门店纬度'];
            $lng        = $shopInfo['门店经度'];
            $name       = $shopInfo['门店名称'];
            $AreaPrefix = $shopInfo['门店所在省'] . '-' . $shopInfo['门店所在市'] . '-' . $shopInfo['区/县'];
            $grade      = null;
        } else {
            if (!isset(SandTableEnum::MODEL_SAND_TABLE_MAPPING[$type])) {
                self::throwErr('未设置的类型');
            }
            $model      = SandTableEnum::MODEL_SAND_TABLE_MAPPING[$type]::query();
            $modelQuery = $model->where('id', $id)->first();
            $orderNo    = $modelQuery->wgNumber;
            $lat        = $modelQuery->lat;
            $lng        = $modelQuery->lng;
            $name       = $modelQuery->nameText;
            $AreaPrefix = $modelQuery->province . '-' . $modelQuery->city . '-' . $modelQuery->district;
            $grade      = $modelQuery->grade;
        }
        //通过经纬度获得天气和温度

        $key      = WangGuiCityByPower::getRandomAmapKey();
        $areaRes  = Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
            ->get(sprintf(config('area.amapGetDistrictByLatLng'), $lng, $lat, $key))
            ->json();
        $adcode   = $areaRes['regeocode']['addressComponent']['adcode'] ?? 0;
        $province = $areaRes['regeocode']['addressComponent']['province'] ?? '';
        $ext      = [];
        if ($adcode) {
            $weatherRes     = Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
                ->get(sprintf(config('weather.amapWeatherUrl'), $adcode, $key))
                ->json();
            $ext['weather'] = ($weatherRes['lives'][0]['weather'] ?? '') . ' ' . (($weatherRes['lives'][0]['temperature'] ?? '') ? ($weatherRes['lives'][0]['temperature'] . '℃') : '');
        }
        $ext['wgName'] = $name;

        if ($openPotential >= ProgrammingEnum::STATUS_SCORE_THREE_POINT_FIVE) {
            $status = ProgrammingEnum::STATUS_EVALUATED_OK;
        } else {
            $status = ProgrammingEnum::STATUS_EVALUATED_NO;
        }

        //点位评估时间
        $evaluateTime = strlen($evaluateTime) ? strtotime($evaluateTime) : time();
        //获得最新的评估记录
        $siteLocationExamineLogModel = OpenShopSiteLocationExamineLogModel::query()
            ->where('orderNo', $orderNo)
            ->with(['wangguiSiteDistrictRel'])
            ->orderByDesc('updatedAt');
        //第二选择状态
        $secondLogModel = $siteLocationExamineLogModel->skip(1)->first();
        $newTimeModel   = $siteLocationExamineLogModel->first();
        if ($newTimeModel != null) {
            $newTime              = $newTimeModel->updatedAt->timestamp;
            $newStatus            = $newTimeModel->openPotential;
            $haveOpenDistrictList = $newTimeModel->wangguiSiteDistrictRel->pluck('id')->toArray();
        } else {
            $newTime              = 0;
            $newStatus            = 0;
            $haveOpenDistrictList = [];
        }


        if (in_array($type, array_merge(ProgrammingEnum::PROGRAMMING_SAND_TABLE_KEY_MAPPING, ['product']))) {
            if ($evaluateId == ($haveOpenDistrictList[0] ?? -1)) {
                if ($secondLogModel && $secondLogModel->updatedAt->timestamp > $evaluateTime) {
                    $modelQuery->update([
                        'status' => $secondLogModel->openPotential,
                    ]);
                } else {
                    $modelQuery->update([
                        'status' => $openPotential,
                    ]);
                }
            } else {
                $modelQuery->update([
                    'status' => $newTime <= $evaluateTime ? $openPotential : $newStatus,
                ]);
            }
        } else {
            if ($evaluateId == ($haveOpenDistrictList[0] ?? -1)) {
                if ($secondLogModel && $secondLogModel->updatedAt->timestamp > $evaluateTime) {
                    self::updateKfShopInfoToCache($id, $secondLogModel->openPotential);
                } else {
                    self::updateKfShopInfoToCache($id, $openPotential);
                }
            } else {
                self::updateKfShopInfoToCache($id, $newTime <= $evaluateTime ? $openPotential : $newStatus);
            }
        }

        if ($newTime < $evaluateTime) {
            //全部置为旧的
            OpenShopSiteLocationExamineLogModel::query()
                ->where('orderNo', $orderNo)
                ->where('createdByUid', $rmsUserId)
                ->update([
                    'isToStore' => OpenShopSiteLocationExamineLogModel::IS_NEW_NO,
                    'updatedAt' => DB::raw('`updatedAt`')
                ]);
        }

        if ($evaluateId) {
            //获得该用户对于此网规点位的评论
            $auditModel = OpenShopSiteLocationExamineLogModel::query()
                ->where('createdByUid', $rmsUserId)
                ->where('orderNo', $orderNo);
            if ($evaluateId == $auditModel->first()->id) {
                if ($auditModel->skip(1)->first() && $evaluateTime < $auditModel->skip(1)->first()->updatedAt->timestamp) {
                    $secondUserAudit             = $auditModel->skip(1)->first();
                    $secondUserAudit->isToStore  = OpenShopSiteLocationExamineLogModel::IS_TO_STORE_YES;
                    $secondUserAudit->timestamps = false;
                    $secondUserAudit->save();
                    $isToStore = OpenShopSiteLocationExamineLogModel::IS_TO_STORE_NO;
                } else {
                    $isToStore = OpenShopSiteLocationExamineLogModel::IS_TO_STORE_YES;
                }
            } else {
                $isToStore = OpenShopSiteLocationExamineLogModel::IS_TO_STORE_NO;
            }


            $examine = OpenShopSiteLocationExamineLogModel::query()->find($evaluateId);
            if (null == $examine) {
                self::throwErr('获取评价内容出错');
            }
            if ($examine->createdByUid != $rmsUserId) {
                self::throwErr('暂无修改权限');
            }
            //删除资源
            ResourcesModel::query()
                ->where('businessId', $evaluateId)
                ->where('module', ResourcesModel::MODULE_TYPE_WG_AUDIT)
                ->where('business', ResourcesModel::BUSINESS_WG_AUDIT)
                ->orWhere('business', ResourcesModel::BUSINESS_OPEN_DISTRICT)
                ->update([
                    "isDeleted" => 1
                ]);
            $examine->timestamps         = false;
            $examine->content            = $content;
            $examine->extra              = json_encode($ext, JSON_UNESCAPED_UNICODE);
            $examine->isToStore          = $isToStore;
            $examine->status             = $status;
            $examine->updatedAt          = $evaluateTime;
            $examine->flowOfPeopleScores = $flowScore;
            $examine->openPotential      = $openPotential;
            $examine->passengerFlowDrive = implode(',', $passengerFlowDrive);
            $examine->customerGroupType  = implode(',', $customerGroupType);
            $examine->save();
        } else {
            $examine = (new OpenShopSiteLocationExamineLogModel([
                'orderNo'            => $orderNo,
                'source'             => in_array($type, ['product', 'kfShop']) ? OpenShopSiteLocationExamineLogModel::SOURCE_OTHER_WG_AUDIT : OpenShopSiteLocationExamineLogModel::SOURCE_WG_AUDIT,
                'content'            => $content,
                'isToStore'          => $newTime > $evaluateTime ? OpenShopSiteLocationExamineLogModel::IS_NEW_NO : OpenShopSiteLocationExamineLogModel::IS_NEW_YES,
                'status'             => $status,
                'type'               => is_numeric($type) ? $type : (int)array_search($type, ProgrammingEnum::PROGRAMMING_SAND_TABLE_KEY_MAPPING),
                'extra'              => json_encode($ext, JSON_UNESCAPED_UNICODE),
                'createdByUid'       => $rmsUserId,
                'updatedByUid'       => $rmsUserId,
                'updatedAt'          => $evaluateTime,
                'openPotential'      => $openPotential,
                'flowOfPeopleScores' => $flowScore,
                'passengerFlowDrive' => implode(',', $passengerFlowDrive),
                'customerGroupType'  => implode(',', $customerGroupType),
            ]))->addData();
        }
        $imgKey   = [];
        $imageArr = [];
        //文件入库
        //图片计数
        $thumbnail = [];
        if (count($businessFile)) {
            foreach ($businessFile as $file) {
                //上传图片用于飞书通知展示
                if ($file['type'] == 'image' && count($thumbnail) <= 9) {
                    $thumbnail[] = ProgrammingService::getFeishuImageKey($file['url']);
                }
                if ($file['type'] == 'video') {
                    ProgrammingService::joinUploadTranscoding(
                        $examine->id,
                        ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        ResourcesModel::BUSINESS_WG_AUDIT,
                        ProgrammingEnum::WANGGUI_BUSINESS_DISTRIBUTION,
                        $file['type'],
                        $file['url'],
                        ResourcesModel::IS_PUBLIC_YES,
                        $rmsUserId
                    );
                } else {
                    $imageArr[] = [
                        'businessId'   => $examine->id,
                        'module'       => ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        'business'     => ResourcesModel::BUSINESS_WG_AUDIT,
                        'name'         => ProgrammingEnum::WANGGUI_BUSINESS_DISTRIBUTION,
                        'url'          => ltrim(parse_url($file['url'], PHP_URL_PATH), '/'),
                        'isPublic'     => ResourcesModel::IS_PUBLIC_YES,
                        'extra'        => json_encode(['type' => $file['type']], JSON_UNESCAPED_UNICODE),
                        'createdByUid' => $rmsUserId,
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            }
        }

        if (count($flowFile)) {
            foreach ($flowFile as $file) {
                //上传图片用于飞书通知展示
                if ($file['type'] == 'image' && count($thumbnail) <= 9) {
                    $thumbnail[] = ProgrammingService::getFeishuImageKey($file['url']);
                }
                if ($file['type'] == 'video') {
                    ProgrammingService::joinUploadTranscoding(
                        $examine->id,
                        ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        ResourcesModel::BUSINESS_WG_AUDIT,
                        ProgrammingEnum::WANGGUI_FLOW_OF_PEOPLE,
                        $file['type'],
                        $file['url'],
                        ResourcesModel::IS_PUBLIC_YES,
                        $rmsUserId
                    );
                } else {
                    $imageArr[] = [
                        'businessId'   => $examine->id,
                        'module'       => ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        'business'     => ResourcesModel::BUSINESS_WG_AUDIT,
                        'name'         => ProgrammingEnum::WANGGUI_FLOW_OF_PEOPLE,
                        'url'          => ltrim(parse_url($file['url'], PHP_URL_PATH), '/'),
                        'isPublic'     => ResourcesModel::IS_PUBLIC_YES,
                        'extra'        => json_encode(['type' => $file['type']], JSON_UNESCAPED_UNICODE),
                        'createdByUid' => $rmsUserId,
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            }
        }

        //$overallMovingLine, $takeawayEvaluation, $floorGuidance,
        if (count($overallMovingLine)) {
            foreach ($overallMovingLine as $file) {
                //上传图片用于飞书通知展示
                if ($file['type'] == 'image' && count($thumbnail) <= 9) {
                    $thumbnail[] = ProgrammingService::getFeishuImageKey($file['url']);
                }
                if ($file['type'] == 'video') {
                    ProgrammingService::joinUploadTranscoding(
                        $examine->id,
                        ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        ResourcesModel::BUSINESS_WG_AUDIT,
                        ProgrammingEnum::WANGGUI_OVERALL_MOVING_LINE,
                        $file['type'],
                        $file['url'],
                        ResourcesModel::IS_PUBLIC_YES,
                        $rmsUserId
                    );
                } else {
                    $imageArr[] = [
                        'businessId'   => $examine->id,
                        'module'       => ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        'business'     => ResourcesModel::BUSINESS_WG_AUDIT,
                        'name'         => ProgrammingEnum::WANGGUI_OVERALL_MOVING_LINE,
                        'url'          => ltrim(parse_url($file['url'], PHP_URL_PATH), '/'),
                        'isPublic'     => ResourcesModel::IS_PUBLIC_YES,
                        'extra'        => json_encode(['type' => $file['type']], JSON_UNESCAPED_UNICODE),
                        'createdByUid' => $rmsUserId,
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            }
        }
        if (count($takeawayEvaluation)) {
            foreach ($takeawayEvaluation as $file) {
                //上传图片用于飞书通知展示
                if ($file['type'] == 'image' && count($thumbnail) <= 9) {
                    $thumbnail[] = ProgrammingService::getFeishuImageKey($file['url']);
                }
                if ($file['type'] == 'video') {
                    ProgrammingService::joinUploadTranscoding(
                        $examine->id,
                        ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        ResourcesModel::BUSINESS_WG_AUDIT,
                        ProgrammingEnum::WANGGUI_TAKEAWAY_EVALUATION,
                        $file['type'],
                        $file['url'],
                        ResourcesModel::IS_PUBLIC_YES,
                        $rmsUserId
                    );
                } else {
                    $imageArr[] = [
                        'businessId'   => $examine->id,
                        'module'       => ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        'business'     => ResourcesModel::BUSINESS_WG_AUDIT,
                        'name'         => ProgrammingEnum::WANGGUI_TAKEAWAY_EVALUATION,
                        'url'          => ltrim(parse_url($file['url'], PHP_URL_PATH), '/'),
                        'isPublic'     => ResourcesModel::IS_PUBLIC_YES,
                        'extra'        => json_encode(['type' => $file['type']], JSON_UNESCAPED_UNICODE),
                        'createdByUid' => $rmsUserId,
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            }
        }
        if (count($floorGuidance)) {
            foreach ($floorGuidance as $file) {
                //上传图片用于飞书通知展示
                if ($file['type'] == 'image' && count($thumbnail) <= 9) {
                    $thumbnail[] = ProgrammingService::getFeishuImageKey($file['url']);
                }
                if ($file['type'] == 'video') {
                    ProgrammingService::joinUploadTranscoding(
                        $examine->id,
                        ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        ResourcesModel::BUSINESS_WG_AUDIT,
                        ProgrammingEnum::WANGGUI_FIOOR_GUIDANCE,
                        $file['type'],
                        $file['url'],
                        ResourcesModel::IS_PUBLIC_YES,
                        $rmsUserId
                    );
                } else {
                    $imageArr[] = [
                        'businessId'   => $examine->id,
                        'module'       => ResourcesModel::MODULE_TYPE_WG_AUDIT,
                        'business'     => ResourcesModel::BUSINESS_WG_AUDIT,
                        'name'         => ProgrammingEnum::WANGGUI_FIOOR_GUIDANCE,
                        'url'          => ltrim(parse_url($file['url'], PHP_URL_PATH), '/'),
                        'isPublic'     => ResourcesModel::IS_PUBLIC_YES,
                        'extra'        => json_encode(['type' => $file['type']], JSON_UNESCAPED_UNICODE),
                        'createdByUid' => $rmsUserId,
                        'updatedByUid' => $rmsUserId,
                    ];
                }
            }
        }
        ResourcesModel::query()->insert($imageArr);

        if (count($canOpenArea)) {
            //修改的id
            $updateIds = collect($canOpenArea)->pluck('id')->filter()->toArray();
            WangguiSiteDistrictModel::query()
                ->whereIn('id', array_diff($haveOpenDistrictList, $updateIds))
                ->update([
                    'isDeleted' => 1
                ]);
            //对于可开区域的调整
            foreach ($canOpenArea as $canOpen) {
                if (isset($canOpen['id'])) {
                    $openAreaModel = WangguiSiteDistrictModel::query()->find($canOpen['id']);
                } else {
                    $openAreaModel = new WangguiSiteDistrictModel();
                }
                $openAreaModel->relationId  = $examine->id;
                $openAreaModel->name        = $canOpen['name'];
                $openAreaModel->isEmptyShop = $canOpen['isEmptyShop'];
                $openAreaModel->save();
                $resourceArr = [];
                foreach ($canOpen['file'] as $file) {
                    if ($file['type'] == 'video') {
                        ProgrammingService::joinUploadTranscoding(
                            $openAreaModel->id,
                            ResourcesModel::MODULE_TYPE_WG_AUDIT,
                            ResourcesModel::BUSINESS_OPEN_DISTRICT,
                            ProgrammingEnum::WANGGUI_OPEN_DISTRICT,
                            $file['type'],
                            $file['url'],
                            ResourcesModel::IS_PUBLIC_YES,
                            $rmsUserId
                        );
                    } else {
                        $resourceArr[] = [
                            'businessId'   => $openAreaModel->id,
                            'module'       => ResourcesModel::MODULE_TYPE_WG_AUDIT,
                            'business'     => ResourcesModel::BUSINESS_OPEN_DISTRICT,
                            'name'         => ProgrammingEnum::WANGGUI_BUSINESS_DISTRIBUTION,
                            'url'          => ltrim(parse_url($file['url'], PHP_URL_PATH), '/'),
                            'isPublic'     => ResourcesModel::IS_PUBLIC_YES,
                            'extra'        => json_encode(['type' => $file['type']], JSON_UNESCAPED_UNICODE),
                            'createdByUid' => $rmsUserId,
                            'updatedByUid' => $rmsUserId,
                        ];
                    }
                }
                ResourcesModel::query()->insert($resourceArr);
            }
        } else {
            WangguiSiteDistrictModel::query()
                ->where('relationId', $evaluateId)
                ->update([
                    'isDeleted' => 1
                ]);
        }

        $areaRobotJson = ConfigModel::query()
            ->where('module', 'wanggui')
            ->where('name', 'areaRobots')
            ->value('value');
        $areaRobotArr  = json_decode($areaRobotJson, true);
        $robotConfig   = [
            'token'  => config('feishu.robots.wangguiAudit.urlToken'),
            'secret' => config('feishu.robots.wangguiAudit.token')
        ];
        foreach ($areaRobotArr as $area => $robot) {
            $provinceLen = mb_strlen($area);
            if (mb_substr($province, 0, $provinceLen) == $area) {
                $robotConfig['token']  = substr($robot['webhook'], (strripos($robot['webhook'], '/') + 1));
                $robotConfig['secret'] = $robot['sign'];
            }
        }

        $json = json_decode(
            sprintf(
                file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/wangguiAudit.json')),
                $rmsUserName,
                $AreaPrefix,
                formatDate($evaluateTime),
                $ext['weather'] ?? '-',
                $openPotential,
                $flowScore,
                \App\Service\OpenShop\Feishu\BaseService::getWangguiAppletUrl($type, $id),
                $status == ProgrammingEnum::STATUS_EVALUATED_OK ? 'green' : 'red',
                '【评估' . (ProgrammingEnum::STATUS_MAPPING[$status] ?? '-') . '】 [' . SandTableEnum::SAND_TABLE_TYPE_MAPPING[$type] . '-' . (ProgrammingEnum::GRADE_MAPPING[$grade] ?? '-') . ' ' . $name . '] 点位评估可开潜力值' . $openPotential . '，请注意',
            ), true
        );


        //获得行
        $rawCount = (int)ceil(count($thumbnail) / 3);

        //获得行图片组件
        $rawPictureComponent = json_decode(file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/threeRawPictureComponent.json')), true);

        //获得单图片
        $singlePictureComponent = json_decode(file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/singlePictureComponent.json')), true);


        $temp       = collect($thumbnail)->map(function ($item) use ($singlePictureComponent) {
            $singlePictureComponent['extra']['img_key'] = $item;
            return $singlePictureComponent;
        })->toArray();
        $totalImage = [];
        for ($i = 0; $i < $rawCount; $i++) {
            $tempRaw                             = $rawPictureComponent;
            $key                                 = $i * 3;
            $tempRaw['columns'][0]['elements'][] = $temp[$key];
            isset($temp[$key + 1]) ? ($tempRaw['columns'][1]['elements'][] = $temp[$key + 1]) : ($a['columns'][1]['elements'] = []);
            isset($temp[$key + 2]) ? ($tempRaw['columns'][2]['elements'][] = $temp[$key + 2]) : ($a['columns'][2]['elements'] = []);
            $totalImage[] = $tempRaw;
        }
        $json['elements'][3]['columns'][0]['elements'] = $totalImage;
        $json['elements'][4]['text']['content']        .= $content;


        if (config('app.env') == 'prod') {
            Factory::feiShu()
                ->setToken($robotConfig['token'])
                ->setSecret($robotConfig['secret'])
                ->setMessage(new \Guanguans\Notify\Messages\FeiShu\CardMessage($json))
                ->send();
        }
        if ($robotConfig['token'] != config('feishu.robots.wangguiAudit.urlToken')) {
            Factory::feiShu()
                ->setToken(config('feishu.robots.wangguiAudit.urlToken'))
                ->setSecret(config('feishu.robots.wangguiAudit.token'))
                ->setMessage(new \Guanguans\Notify\Messages\FeiShu\CardMessage($json))
                ->send();
        }
    }


    /**
     * 容错文件
     * @param $fileList
     * @param $cover
     * @return array[]
     */
    public static function getFileList($fileList, $cover): array
    {
        return empty($fileList) ? [$cover ? ['url' => $cover, 'type' => 'image'] : ['url' => 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png', 'type' => 'image']] : $fileList;
    }


    /**
     * 根据市获得市下面区的边界信息
     * @param $cityCode
     * @return array
     */
    public static function getBoundaryByCity($cityCode): array
    {
        return Cache::remember('openShop:sandTable:districts:cache:area:dot' . $cityCode, 86000, function () use ($cityCode) {
            ini_set('memory_limit', '512M');
            return CityTerritorialBoundaryModel::query()
                ->where('level', 'city')
                ->where('adcode', $cityCode)
                ->with(['cityTerritorialBoundaryRelByCity'])
                ->get()
                ->map(function (CityTerritorialBoundaryModel $cityTerritorialBoundaryModel) {
                    return [
                        'cityName'  => str_replace('城区', '', $cityTerritorialBoundaryModel->name),
                        'cityCode'  => $cityTerritorialBoundaryModel->adcode,
                        'centerLng' => $cityTerritorialBoundaryModel->centerLongitude,
                        'centerLat' => $cityTerritorialBoundaryModel->centerLatitude,
                        'district'  => $cityTerritorialBoundaryModel->cityTerritorialBoundaryRelByCity->map(function (CityTerritorialBoundaryModel $territorialBoundaryModel) {
                            $boundary = [];
                            try {
                                foreach (explode(';', $territorialBoundaryModel->polyline) as $value) {
                                    $temp       = explode(',', $value);
                                    $boundary[] = [
                                        'lng' => $temp[0],
                                        'lat' => $temp[1],
                                    ];
                                }
                            } catch (\Exception $exception) {

                            }
                            return [
                                'districtName' => str_replace('城区', '', $territorialBoundaryModel->name),
                                'districtCode' => $territorialBoundaryModel->adcode,
                                'centerLng'    => $territorialBoundaryModel->centerLongitude,
                                'centerLat'    => $territorialBoundaryModel->centerLatitude,
                                'boundary'     => $boundary
                            ];
                        })
                    ];
                })->toArray();
        });
    }


    /**
     * 获取默认封面图
     * @param string $name
     * @return string
     */
    public static function getDefaultCoverImage(string $name): string
    {
        $cover = (string)ResourcesModel::query()
            ->where('module', ResourcesModel::MODULE_TYPE_WG_AUDIT)
            ->where('business', ResourcesModel::BUSINESS_WG_AUDIT)
            ->where('businessId', 0)
            ->where('name', $name)
            ->value('url');
        return strlen($cover) ? picturePath($cover) : SandTableEnum::DEFAULT_COVER_IMAGE_BASIC;
    }

    /**
     * 评估结果同步缓存
     * @param $shopCode
     * @param $status
     * @return void
     */
    public static function updateKfShopInfoToCache($shopCode, $status)
    {
        if (Cache::has('openShop:sandTable:kfShop:Cache:code:' . $shopCode)) {
            $data           = Cache::get('openShop:sandTable:kfShop:Cache:code:' . $shopCode);
            $data['status'] = $status;
            Cache::put('openShop:sandTable:kfShop:Cache:code:' . $shopCode, $data, 86400);
        }
    }


    /**
     * 获得夸父门店卡片信息 数据来源观远
     * @param int|string $shopCode 门店code
     * @param array $maxItem 观远门店最近营业额数据
     * @return array
     */
    public static function getKfShopCardInfo($shopCode, array $maxItem): array
    {
        // 准备弃用的方式
//        $shopCode = str_pad($shopCode, 4, '0', STR_PAD_LEFT);
//        try {
//            $shop     = GuanyuanDataService::newShopList($shopCode)[0] ?? [];
//        } catch (\Exception $exception) {
//            $shop     = [];
//        }

        // 优化后的方式

        $guanyuanShopModel = GuanyuanSyncShopListModel::query()
            ->where('code', (int)$shopCode)
            ->first();

        if (null === $guanyuanShopModel) {
            self::throwErr('获得观远门店数据失败');
        }
        //夸父门店
        $wgNumber = 'KFZC' . str_pad($shopCode, 7, '0', STR_PAD_LEFT);
        $fileList = []; //图片List
        $status   = '待评估';
        $cover    = self::getDefaultCoverImage($wgNumber);  //默认封面图

        //获得评估日志
        OpenShopSiteLocationExamineLogModel::query()
            ->where('orderNo', $wgNumber)
            ->where('source', OpenShopSiteLocationExamineLogModel::SOURCE_OTHER_WG_AUDIT)
            ->orderBy('updatedAt')
            ->with(['resourceRelUsedToShow', 'wangguiSiteDistrictRel.resourceRel'])
            ->get()
            ->each(function (OpenShopSiteLocationExamineLogModel $locationExamineLogModel) use (&$status, &$cover) {
                $status = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-';
                $locationExamineLogModel->resourceRelUsedToShow->each(function (ResourcesModel $resourcesModel) use (&$file, &$fileList, &$status, &$cover) {
                    if ((json_decode($resourcesModel->extra, true)['type'] ?? '') == 'image') {
                        $cover = picturePath($resourcesModel->url);
                    }
                    // $fileList[] = ['url' => picturePath($resourcesModel->url), 'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')];
                });
            });

        // 根据开店订单号获得cruise的ID
        $cruiseId = CruiseOrderModel::query()
            ->where('orderNo', $guanyuanShopModel->orderNo)
            ->value('id');


        // 开业报告图片
        ResourcesModel::query()->where('businessId', $cruiseId)
            ->where('module', ResourcesModel::MODULE_TYPE_CRUISE)
            ->where('business', ResourcesModel::BUSINESS_CRUISE_ORDERS)
            ->each(function (ResourcesModel $resourcesModel) use (&$fileList){
                $fileList[] = picturePath($resourcesModel->url);
            });

        return [
            'cover'    => $cover,
            'fileList' => $fileList,
            'name'     => $guanyuanShopModel->name,
            'label'    => collect([
                $guanyuanShopModel->status,
                $guanyuanShopModel->siteLocationType ?: null,
                $guanyuanShopModel->storeType ?: null,
                $guanyuanShopModel->cashierSystem ?: null
            ])->filter()->values()->toArray(),
            'grade'    => $maxItem['shopGrade'] ?? '',
            'lng'      => $guanyuanShopModel->lng,
            'lat'      => $guanyuanShopModel->lat,
            'province' => $guanyuanShopModel->province,
            'city'     => $guanyuanShopModel->city,
            'district' => $guanyuanShopModel->district,
            'address'  => $guanyuanShopModel->address,
            'status'   => $status,
            'type'     => 'kfShop',
            'key'      => ProgrammingEnum::KF_SHOP_SAND_TABLE_KEY_MAPPING[ProgrammingEnum::KF_SHOP_STATUS_REVERSE_MAPPING[$guanyuanShopModel->status] ?? 0] ?? 'kfShop',
        ];
    }


    /**
     * 根据高德返回的城市信息获得每个点位信息（聚合）
     * @param $cityInfo
     * @return array
     */
    public static function getCityDistrictDotInfo($cityInfo): array
    {
        //循环每个区获得区内点位信息
        $districtNameLists = array_column($cityInfo['districts'], 'name', 'adcode');
        $tempDot           = [];
        $cityName          = mb_substr($cityInfo['name'], 0, 2);
        //门店信息
        try {
            $kfShop  = GuanyuanDataService::newShopList();
        } catch (\Exception $exception) {
            $kfShop = [];
        }
        foreach ($kfShop as $shop) {
            if (in_array($shop['区/县'], $districtNameLists) && in_array($shop['状态'], ProgrammingEnum::KF_SHOP_STATUS_SELECT_MAPPING) && mb_strpos($shop['门店所在市'], $cityName) !== false && $shop['门店经度'] && $shop['门店纬度']) {
                $tempDot[ProgrammingEnum::KF_SHOP_SAND_TABLE_KEY_MAPPING[array_search($shop['状态'], ProgrammingEnum::KF_SHOP_STATUS_SELECT_MAPPING)] ?? 'kfShop'][] = [
                    'name'   => $shop['门店名称'],
                    'id'     => (int)$shop['铺位号'],
                    'lng'    => $shop['门店经度'],
                    'lat'    => $shop['门店纬度'],
                    'type'   => SandTableEnum::KF_MODEL_SAND_TABLE,
                    'key'    => ProgrammingEnum::KF_SHOP_SAND_TABLE_KEY_MAPPING[ProgrammingEnum::KF_SHOP_STATUS_REVERSE_MAPPING[$shop['状态']] ?? 0] ?? 'kfShop',
                    'adcode' => (int)array_search($shop['区/县'], $districtNameLists),
                ];
            }
        }

        foreach (SandTableEnum::MAP_MODEL_MAPPING as $namespace) {
            $model = $namespace::query();
            $model->where('city', 'like', "$cityName%")
                ->whereIn('district', $districtNameLists)
                ->get()
                ->each(function ($modelQuery) use (&$tempDot, $districtNameLists) {
                    switch (get_class($modelQuery)) {
                        case SiteLocationMallModel::class:
                        case MapNationalStreetModel::class:
                        case MapNationalCommunityModel::class:
                        case MapTownshipPlanAreaModel::class:
                        case MapNationalUniversitiesModel::class:
                        case MapNationalIndustrialParkModel::class:
                            $type = $key = $k = (string)array_search(get_class($modelQuery), SandTableEnum::MODEL_SAND_TABLE_MAPPING);
                            break;
                        case MapNationalBrandShopModel::class:
                            $key  = $k = ProgrammingEnum::BRAND_SHOP_MAPPING[$modelQuery->brand] ?? 'product';
                            $type = (string)array_search(get_class($modelQuery), SandTableEnum::MODEL_SAND_TABLE_MAPPING);
                            break;
                        default:
                            $type = $key = $k = 'other';
                    }
                    $tempData = [
                        'id'     => $modelQuery->id,
                        'name'   => $modelQuery->nameText,
                        'lng'    => $modelQuery->lng,
                        'lat'    => $modelQuery->lat,
                        'type'   => $type,
                        'key'    => $key,
                        'adcode' => (int)array_search($modelQuery->district, $districtNameLists),
                        'grade'  => $modelQuery->grade,
                        'status' => ProgrammingEnum::STATUS_SCORE_SAND_TABLE_MAPPING[(string)$modelQuery->status] ?? -1,
                    ];
                    $boundary = ['boundary' => []];
                    if (get_class($modelQuery) == MapNationalStreetModel::class) {
                        $boundary = json_decode($modelQuery->coords, true);
                        $boundary = collect($boundary)->map(function ($arr) {
                            if (2 != count($arr)) {
                                return null;
                            }
                            return [
                                'lng' => $arr[0],
                                'lat' => $arr[1],
                            ];
                        })->filter()->toArray();
                        $boundary = ['boundary' => $boundary];
                    }
                    if (get_class($modelQuery) == MapNationalCommunityModel::class) {
                        $boundary = json_decode($modelQuery->coords, true);
                        $boundary = collect($boundary)->map(function ($arr) {
                            if (2 != count($arr)) {
                                return null;
                            }
                            return [
                                'lng' => $arr[0],
                                'lat' => $arr[1],
                            ];
                        })->filter()->toArray();
                        $boundary = ['boundary' => $boundary];
                    }
                    if (get_class($modelQuery) == MapNationalUniversitiesModel::class) {
                        $boundary = json_decode($modelQuery->boundary, true);
                        $boundary = collect($boundary)->map(function ($arr) {
                            if (2 != count($arr)) {
                                return null;
                            }
                            return [
                                'lng' => $arr[0],
                                'lat' => $arr[1],
                            ];
                        })->filter()->toArray();
                        $boundary = ['boundary' => $boundary];
                    }
                    $tempData      = array_merge($tempData, $boundary);
                    $tempDot[$k][] = $tempData;
                });
        }
        return $tempDot;
    }



    /**
     * @param $type
     * @param $id
     * @param $rmsUserId
     * @return array
     * @throws GuzzleException
     * @throws \Exception
     */
    public static function floatCard($type, $id, $rmsUserId): array
    {
        $data               = [];
        $auditEffectiveTime = ConfigService::config('wanggui', 'auditEffectiveTime')['auditEffectiveTime'] ?? 0;
        //通过type和ID获得模型详情
        if ($type == SandTableEnum::KF_MODEL_SAND_TABLE) {
            if (Cache::has('openShop:sandTable:kfShop:Cache:code:' . (int)$id)) {
                return Cache::get('openShop:sandTable:kfShop:Cache:code:' . (int)$id);
            }
            $shopCode = str_pad($id, 4, '0', STR_PAD_LEFT);
            //夸父门店
            $wgNumber = 'KFZC' . str_pad($shopCode, 7, '0', STR_PAD_LEFT);

            $flowPeople   = 0;  //人流打分
            $openDistrict = 0;  //可开区域打分
            $fileList     = []; //图片List
            $status       = '待评估';
            $cover        = self::getDefaultCoverImage($wgNumber);  //默认封面图
            //获得评估日志
            $logModel  = OpenShopSiteLocationExamineLogModel::query()
                ->where('orderNo', $wgNumber)
                ->where('source', OpenShopSiteLocationExamineLogModel::SOURCE_OTHER_WG_AUDIT)
                ->orderBy('updatedAt')
                ->with(['resourceRelUsedToShow', 'wangguiSiteDistrictRel.resourceRel'])
                ->get();
            $body      = RmsUserService::getRmsUserInfoByUserIds($logModel->pluck('createdByUid')->toArray())['data'] ?? [];
            $userNames = array_column($body, 'username', 'id');
            $logs      = $logModel->map(function (OpenShopSiteLocationExamineLogModel $locationExamineLogModel) use (&$flowPeople, &$openDistrict, &$fileList, $rmsUserId, $auditEffectiveTime, &$status, $userNames, &$cover) {
                $file         = [];
                $flowPeople   = $locationExamineLogModel->flowOfPeopleScores;
                $openDistrict = $locationExamineLogModel->openPotential;
                $status       = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-';
                $locationExamineLogModel->resourceRelUsedToShow->each(function (ResourcesModel $resourcesModel) use (&$file, &$fileList, &$status, &$cover) {
                    if ((json_decode($resourcesModel->extra, true)['type'] ?? '') == 'image') {
                        $cover = picturePath($resourcesModel->url);
                    }
                    $file[$resourcesModel->name][] = ['url' => picturePath($resourcesModel->url), 'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')];
                    $fileList[]                    = ['url' => picturePath($resourcesModel->url), 'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')];
                });
                return array_merge([
                    'id'                 => $locationExamineLogModel->id,
                    'username'           => $userNames[$locationExamineLogModel->createdByUid] ?? '-',
                    'status'             => $locationExamineLogModel->status,
                    'openPotential'      => $locationExamineLogModel->openPotential,
                    'flowOfPeopleScores' => $locationExamineLogModel->flowOfPeopleScores,
                    'statusText'         => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-',
                    'createdAt'          => $locationExamineLogModel->updatedAt->format('Y-m-d H:i'),
                    'evaluateTime'       => $locationExamineLogModel->updatedAt->format('Y-m-d H:i'),
                    'content'            => $locationExamineLogModel->content,
                    'isUpdate'           => $locationExamineLogModel->createdByUid == $rmsUserId && time() < ($locationExamineLogModel->updatedAt->timestamp + $auditEffectiveTime * 3600),
                    'weather'            => DateTool::cnWeekOfDay($locationExamineLogModel->updatedAt->dayOfWeek) . ' ' . (json_decode($locationExamineLogModel->extra, true)['weather'] ?? ''),
                    'openDistrictList'   => $locationExamineLogModel->wangguiSiteDistrictRel->map(function (WangguiSiteDistrictModel $wangguiSiteDistrictModel) {
                        return [
                            'id'              => $wangguiSiteDistrictModel->id,
                            'name'            => $wangguiSiteDistrictModel->name,
                            'isEmptyShop'     => $wangguiSiteDistrictModel->isEmptyShop,
                            'isEmptyShopText' => WangguiSiteDistrictModel::IS_EMPTY_SHOP_MAPPING[$wangguiSiteDistrictModel->isEmptyShop] ?? '',
                            'file'            => $wangguiSiteDistrictModel->resourceRel->map(function (ResourcesModel $resourcesModel) {
                                return [
                                    'url'  => picturePath($resourcesModel->url),
                                    'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')
                                ];
                            })
                        ];
                    })->toArray(),
                ], $file);
            })->toArray();

            //            if (Cache::has('openShop:sandTable:kfShop:Cache:code:' . (int)$id)) {
            //                $data = Cache::get('openShop:sandTable:kfShop:Cache:code:' . (int)$id);
            //                $data = array_merge(
            //                    $data,
            //                    [
            //                        'score'    => [
            //                            '可开潜力值:' . $openDistrict,
            //                            '人流量:' . $flowPeople,
            //                        ],
            //                        'logs'     => $logs
            //                    ]
            //                );
            //            } else {


            $shop = GuanyuanSyncShopListModel::query()
                ->where('code', (int)$shopCode)
                ->first();

            if (null === $shop) {
                self::throwErr('获得观远门店数据失败');
            }

            // 获得该门店最近的营业额
            $turnover = GuanyuanSyncShopBusinessModel::query()
                ->where('code', $shopCode)
                ->orderByDesc('date')
                ->first();

            try {
                $shopId         = (int)optional(optional(OpenShopSignOrderModel::query()->where('shopCode', $id)->where('status', '!=', SignOrderEnum::ORDER_STATUS_NO)->with(['mainProcessRel'])->first())->mainProcessRel)->shopId;
                $showTimeTab    = 5;
                $showStartAt    = Carbon::now()->subDays(30)->startOfDay()->timestamp;
                $showEndAt      = Carbon::today()->startOfDay()->timestamp;
                $compareTimeTab = 4;
                $compareStartAt = Carbon::now()->subDays(60)->startOfDay()->timestamp;
                $compareEndAt   = Carbon::now()->subDays(30)->startOfDay()->timestamp;
                //获取折线图
                $res = (new RmsShopApi())->indexCharts($shopId, $showTimeTab, $showStartAt, $showEndAt, $compareTimeTab, $compareStartAt, $compareEndAt);
                if ($res['code'] == 1) {
                    $charts = $res['data'];
                } else {
                    $charts = [];
                }
            } catch (\Exception $exception) {
                $charts = [];
            }

            // 添加预测数据折线图
            if (count($charts)) {
                $charts[] = [
                    'text'           => '预测',
                    'statisticsType' => 1,
                    'numType'        => 1,
                    'lists'          => WangguiApiService::getHistoricalPredictionByWgNumber(str_pad($id, 4, "0", STR_PAD_LEFT))
                ];
            }


            $data = [
                'cover'         => $cover,
                'fileList'      => self::getFileList($fileList, $cover),
                'name'          => $shop->name,
                'label'         => collect([
                    $shop->status,
                    $shop->siteLocationType ?: null,
                    $shop->storeType ?: null,
                    $shop->cashierSystem ?: null
                ])->filter()->values()->toArray(),
                'takeawayScore' => '外卖评分: 美团' . (optional($turnover)->mtRating ?: '-') . ' | 饿了么' . (optional($turnover)->elmRating ?: '-'),
                'special'       => [
                    [
                        'name'  => '开业日期',
                        'value' => $shop->openBusinessDate ?: '-',
                    ],
                    [
                        'name'  => '已开业',
                        'value' => $shop->openBusinessDate ? Carbon::parse($shop->openBusinessDate)->diff(Carbon::now())->format('%y年%m个月') : '-'
                    ]
                ],
                'grade'         => optional($turnover)->shopGrade ?: '',
                'lng'           => $shop->lng,
                'lat'           => $shop->lat,
                'province'      => $shop->province,
                'city'          => $shop->city,
                'district'      => $shop->district,
                'address'       => $shop->address,
                'status'        => $status,
                'type'          => 'kfShop',
                'key'           => ProgrammingEnum::KF_SHOP_SAND_TABLE_KEY_MAPPING[ProgrammingEnum::KF_SHOP_STATUS_REVERSE_MAPPING[$shop->status]] ?? 'kfShop',
                'score'         => [
                    '可开潜力值:' . $openDistrict,
                    '人流量:' . $flowPeople,
                ],
                'shopInfo'      => [
                    [
                        'name'  => '门店面积',
                        'value' => optional($turnover)->area ? (optional($turnover)->area . '㎡') : '-',
                    ], [
                        'name'  => '员工人数',
                        'value' => optional($turnover)->employeesNum ?: '-',
                    ], [
                        'name'  => '房租成本',
                        'value' => optional($turnover)->rent ? ('¥' . optional($turnover)->rent) : '-',
                    ], [
                        'name'  => '人力成本',
                        'value' => optional($turnover)->artificial ? ('¥' . optional($turnover)->artificial) : '-',
                    ]
                ],
                'phone'         => [],
                'charts'        => $charts,
                'logs'          => $logs
            ];

        } else {
            //网规点位详情
            if (!isset(SandTableEnum::MODEL_SAND_TABLE_MAPPING[$type])) {
                self::throwErr('类型错误');
            }
            $model      = SandTableEnum::MODEL_SAND_TABLE_MAPPING[$type]::query();
            $modelQuery = $model->where('id', $id)->with(['logRel.resourceRelUsedToShow', 'logRel.resourceRelByCover'])->first();
            if ($modelQuery == null) {
                self::throwErr('获取网规点位详情失败');
            }
            $cover = self::getDefaultCoverImage($modelQuery->wgNumber);   //先获得地图图片
            optional($modelQuery->logRel)->each(function (OpenShopSiteLocationExamineLogModel $locationExamineLogModel) use (&$cover) {
                $locationExamineLogModel->resourceRelByCover->each(function (ResourcesModel $resourcesModel) use (&$cover) {
                    $fileType = json_decode($resourcesModel->extra, true)['type'] ?? '-';
                    if ($resourcesModel->name == ProgrammingEnum::WANGGUI_BUSINESS_DISTRIBUTION && $fileType == 'image') {
                        $cover = picturePath($resourcesModel->url);
                    }
                });
            });


            $fileList   = [];
            $flowPeople = 0;
            $status     = '待评估';
            $wgNumber   = $modelQuery->wgNumber;
            if ($type == 'product') {
                $logsModel  = OpenShopSiteLocationExamineLogModel::query()
                    ->where('source', OpenShopSiteLocationExamineLogModel::SOURCE_OTHER_WG_AUDIT)
                    ->orderBy('updatedAt', 'asc')
                    ->with(['resourceRelUsedToShow', 'wangguiSiteDistrictRel.resourceRel'])
                    ->where('orderNo', $wgNumber)
                    ->get();
                $logUserIds = (array)optional(optional($modelQuery->logRel)->pluck('createdByUid'))->toArray();
                $body       = RmsUserService::getRmsUserInfoByUserIds($logUserIds)['data'] ?? [];
                $userNames  = array_column($body, 'username', 'id');
                $logs       = $logsModel->map(function (OpenShopSiteLocationExamineLogModel $locationExamineLogModel) use (&$flowPeople, &$openDistrict, &$fileList, $rmsUserId, $auditEffectiveTime, &$status, $userNames) {
                    $file         = [];
                    $flowPeople   = $locationExamineLogModel->flowOfPeopleScores;
                    $openDistrict = $locationExamineLogModel->openPotential;
                    $status       = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-';
                    $locationExamineLogModel->resourceRelUsedToShow->each(function (ResourcesModel $resourcesModel) use (&$file, &$fileList) {
                        $file[$resourcesModel->name][] = ['url' => picturePath($resourcesModel->url), 'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')];
                        $fileList[]                    = ['url' => picturePath($resourcesModel->url), 'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')];
                    });
                    return array_merge([
                        'id'                 => $locationExamineLogModel->id,
                        'username'           => $userNames[$locationExamineLogModel->createdByUid] ?? '-',
                        'status'             => $locationExamineLogModel->status,
                        'openPotential'      => $locationExamineLogModel->openPotential,
                        'flowOfPeopleScores' => $locationExamineLogModel->flowOfPeopleScores,
                        'statusText'         => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-',
                        'createdAt'          => $locationExamineLogModel->updatedAt->format('Y-m-d H:i'),
                        'evaluateTime'       => $locationExamineLogModel->updatedAt->format('Y-m-d H:i'),
                        'content'            => $locationExamineLogModel->content,
                        'isUpdate'           => $locationExamineLogModel->createdByUid == $rmsUserId && time() < ($locationExamineLogModel->updatedAt->timestamp + $auditEffectiveTime * 3600),
                        'weather'            => DateTool::cnWeekOfDay($locationExamineLogModel->updatedAt->dayOfWeek) . ' ' . (json_decode($locationExamineLogModel->extra, true)['weather'] ?? ''),
                        'openDistrictList'   => $locationExamineLogModel->wangguiSiteDistrictRel->map(function (WangguiSiteDistrictModel $wangguiSiteDistrictModel) {
                            return [
                                'id'              => $wangguiSiteDistrictModel->id,
                                'name'            => $wangguiSiteDistrictModel->name,
                                'isEmptyShop'     => $wangguiSiteDistrictModel->isEmptyShop,
                                'isEmptyShopText' => WangguiSiteDistrictModel::IS_EMPTY_SHOP_MAPPING[$wangguiSiteDistrictModel->isEmptyShop] ?? '',
                                'file'            => $wangguiSiteDistrictModel->resourceRel->map(function (ResourcesModel $resourcesModel) {
                                    return [
                                        'url'  => picturePath($resourcesModel->url),
                                        'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')
                                    ];
                                })
                            ];
                        })
                    ], $file);
                })->toArray();
            } else {
                $logUserIds = (array)optional(optional($modelQuery->logRel)->pluck('createdByUid'))->toArray();
                $body       = RmsUserService::getRmsUserInfoByUserIds($logUserIds)['data'] ?? [];
                $userNames  = array_column($body, 'username', 'id');
                $logs       = (array)optional(
                    optional($modelQuery->logRel)->map(function (OpenShopSiteLocationExamineLogModel $locationExamineLogModel) use ($rmsUserId, $userNames, $auditEffectiveTime, $cover, &$fileList, &$flowPeople, &$status) {
                        $file       = [];
                        $flowPeople = $locationExamineLogModel->flowOfPeopleScores;
                        $status     = ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-';
                        $locationExamineLogModel->resourceRelUsedToShow->each(function (ResourcesModel $resourcesModel) use (&$file, &$fileList) {
                            $file[$resourcesModel->name][] = ['url' => picturePath($resourcesModel->url), 'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')];
                            $fileList[]                    = ['url' => picturePath($resourcesModel->url), 'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')];
                        });
                        return array_merge([
                            'id'                 => $locationExamineLogModel->id,
                            'username'           => $userNames[$locationExamineLogModel->createdByUid] ?? '-',
                            'status'             => $locationExamineLogModel->status,
                            'openPotential'      => $locationExamineLogModel->openPotential,
                            'flowOfPeopleScores' => $locationExamineLogModel->flowOfPeopleScores,
                            'statusText'         => ProgrammingEnum::STATUS_SCORE_MAPPING[(string)$locationExamineLogModel->openPotential] ?? '-',
                            'createdAt'          => $locationExamineLogModel->updatedAt->format('Y-m-d H:i'),
                            'evaluateTime'       => $locationExamineLogModel->updatedAt->format('Y-m-d H:i'),
                            'content'            => $locationExamineLogModel->content,
                            'isUpdate'           => $locationExamineLogModel->createdByUid == $rmsUserId && time() < ($locationExamineLogModel->updatedAt->timestamp + $auditEffectiveTime * 3600),
                            'weather'            => DateTool::cnWeekOfDay($locationExamineLogModel->updatedAt->dayOfWeek) . ' ' . (json_decode($locationExamineLogModel->extra, true)['weather'] ?? ''),
                            'openDistrictList'   => $locationExamineLogModel->wangguiSiteDistrictRel->map(function (WangguiSiteDistrictModel $wangguiSiteDistrictModel) {
                                return [
                                    'id'              => $wangguiSiteDistrictModel->id,
                                    'name'            => $wangguiSiteDistrictModel->name,
                                    'isEmptyShop'     => $wangguiSiteDistrictModel->isEmptyShop,
                                    'isEmptyShopText' => WangguiSiteDistrictModel::IS_EMPTY_SHOP_MAPPING[$wangguiSiteDistrictModel->isEmptyShop] ?? '',
                                    'file'            => $wangguiSiteDistrictModel->resourceRel->map(function (ResourcesModel $resourcesModel) {
                                        return [
                                            'url'  => picturePath($resourcesModel->url),
                                            'type' => (json_decode($resourcesModel->extra, true)['type'] ?? '')
                                        ];
                                    })
                                ];
                            })
                        ], $file);
                    })
                )->toArray();
            }

            switch ($type) {
                case 'mallProgramming':
                    $label   = array_merge(
                        (mb_strlen($modelQuery->topList) ? [$modelQuery->topList] : [])
                    );
                    $special = [
                        [
                            'name'  => '店铺总数',
                            'value' => $modelQuery->shopTotalCount,
                        ], [
                            'name'  => '美食店铺占比',
                            'value' => $modelQuery->foodRatio ? ($modelQuery->foodRatio * 100 . '%') : 0,
                        ], [
                            'name'  => '夸父门店数',
                            'value' => $modelQuery->shopNum,
                        ]
                    ];
                    break;
                case 'streetProgramming':
                case 'communityProgramming':
                case 'parkProgramming':
                    $label   = [];
                    $special = [
                        [
                            'name'  => '夸父门店数',
                            'value' => $modelQuery->shopNum,
                        ]
                    ];
                    break;
                case 'townProgramming':
                    $label   = array_merge(
                        ($modelQuery->shopCountRank ? ['商超数排名第' . $modelQuery->shopCountRank] : []),
                        ($modelQuery->qianqiangTownRank ? ['千强镇第' . $modelQuery->qianqiangTownRank . '名'] : [])
                    );
                    $special = [
                        [
                            'name'  => '人口密度',
                            'value' => round($modelQuery->peopleDensity, 1),
                        ], [
                            'name'  => '人口密度排名',
                            'value' => $modelQuery->peopleDensityRank,
                        ], [
                            'name'  => '夸父门店数',
                            'value' => $modelQuery->shopNum,
                        ]
                    ];
                    break;
                case 'schoolProgramming':
                    $label   = array_merge(
                        ($modelQuery->doubleFirstClass == '是' ? ['双一流'] : []),
                        ($modelQuery->project985 == '是' ? ['985'] : []),
                        ($modelQuery->project211 == '是' ? ['211'] : []),
                        ($modelQuery->strongBasis == '是' ? ['强基'] : [])
                    );
                    $special = [
                        [
                            'name'  => '院校类型',
                            'value' => $modelQuery->schoolType,
                        ], [
                            'name'  => '面积',
                            'value' => $modelQuery->space . '亩',
                        ], [
                            'name'  => '夸父门店数',
                            'value' => $modelQuery->shopNum,
                        ]
                    ];
                    break;
                case 'product':
                    $label   = [];
                    $special = [
                        [
                            'name'  => '开业时间',
                            'value' => $modelQuery->openingTime ?: '-',
                        ], [
                            'name'  => '营业时间',
                            'value' => $modelQuery->openingTime ? Carbon::parse($modelQuery->openingTime)->diff(Carbon::now())->format('%y年%m个月') : '-'
                        ]
                    ];
                    $key     = ProgrammingEnum::BRAND_SHOP_MAPPING[$modelQuery->brand] ?? 'product';
                    break;
                default:
                    $label   = [];
                    $special = [];
            }



            $data = [
                'cover'    => $cover ?: 'https://file.51kuafu.com/5e/d4/9a6e37f514dd4df64f0a4412fc378ed764206a6f1b5c8ca8f3cbe2c2c9a4.png',
                'fileList' => self::getFileList($fileList, $cover),
                'name'     => $modelQuery->nameText,
                'isMall'   => $type == 'mallProgramming',
                'type'     => $type,
                'key'      => isset($key) ?: (string)array_search(get_class($modelQuery), SandTableEnum::MODEL_SAND_TABLE_MAPPING),
                'status'   => $status,
                'wgNumber' => $modelQuery->wgNumber,
                'label'    => $label,
                'settleIn' => $modelQuery->settle ? '已入驻' : '',
                'special'  => $special,
                'grade'    => ProgrammingEnum::GRADE_MAPPING[$modelQuery->grade] ?? '',
                'lng'      => $modelQuery->lng,
                'lat'      => $modelQuery->lat,
                'province' => $modelQuery->province,
                'city'     => $modelQuery->city,
                'district' => $modelQuery->district,
                'address'  => $modelQuery->address,
                'recommendFloor'  => $modelQuery->recommendFloor ?: '',
                'score'    => [
                    '可开潜力值:' . $modelQuery->status,
                    '人流量:' . $flowPeople,
                ],
                'phone'    => $modelQuery->phone ? explode('|', $modelQuery->phone) : [],
                'logs'     => $logs
            ];
        }
        //获得外卖预估
        $distance = 3;  //默认3km
        // 外卖预估数据
        if (!$data['lng'] || !$data['lat']) {
            $takeOutInfo = [
                'elmSalesVolume'                   => '',
                'takeOutDoubleSalesVolume'         => '',
                'takeOutDoubleSalesVolumeReceived' => '',
                'mtSalesVolume'                    => '',
            ];
        } else {
            $takeOutData = (new WaiMaiAnalysisService())
                ->setLngLat($data['lng'], $data['lat'], $distance);
            $estimate    = $takeOutData->calcEstimateData();
            $takeOutInfo = [
                'takeOutDoubleSalesVolume'         => (int)(array_sum($estimate['estimate']) * 0.8) . '~' . (int)(array_sum($estimate['estimate']) * 1.2),
                'takeOutDoubleSalesVolumeReceived' => ((int)(array_sum($estimate['estimate']) * 0.8) * 30) . '~' . ((int)(array_sum($estimate['estimate']) * 1.2) * 30),
                'mtSalesVolume'                    => (int)($estimate['estimate']['mt'] * 0.8) . '~' . (int)($estimate['estimate']['mt'] * 1.2),
                'elmSalesVolume'                   => (int)($estimate['estimate']['elm'] * 0.8) . '~' . (int)($estimate['estimate']['elm'] * 1.2),
            ];
        }
        $data['takeOutInfo'] = $takeOutInfo;

        return $data;
    }

}
